sql优化之临时表的使用

需求:明天4点定时导出execl,展示当天登录人数详情,数据量900左右,涉及表7个

原sql:

with temp(userid,FirstLoginTime,LastLoginTime) 
as( select a.userid, min(a.LastLoginTM) as FirstLoginTime, max(a.LastLoginTM) as LastLoginTime from TLoginRecord a,
TUsers b where a.UserID=b.UserID and b.IsRobot=0 and 
a.LastLoginTM>='2018-01-17 00:00:00' and a.LastLoginTM<='2018-01-17 23:59:59' group by a.userid),

tempA (GameCount,OnlineTime,UserID)as(
select count(*) as GameCount,isnull(sum(GameTime),0)/60 as OnlineTime,UserID from TChangeRecord t1 inner join TChangeRecordUser t2 on 
t1.ID=t2.RecordIndex and EndTime>='2018-01-17 00:00:00' and EndTime<='2018-01-17 23:59:59' group by UserID),

tempB(UserID,TotalPayMoney)as
(select Users_ids as userid,SUM(PayMoney) as TotalPayMoney from Web_RMBCost where PaySuccess=1 
and addtime>='2018-01-17 00:00:00' and addtime<='2018-01-17 23:59:59' group by Users_ids) 
select '2018-02-26' as Reportdate, tp.*,tu.NickName,tf.superid,ISnull(ta.OnlineTime,0) OnlineTime,
Isnull(ta.GameCount,0) GameCount ,ISnull(tb.TotalPayMoney,0) TotalPayMoney,
sy.ShuLiang as ShuLiang from temp tp left join TUsers tu on tp.userid=tu.UserID 
left join TUserInfo tf on tp.userid=tf.UserID 
left join tempA ta on tp.userid=ta.UserID 
left join tempB tb on tp.userid=tb.UserID 
left join Shop_YongHuShangPin sy on tp.userid=sy.Userid and sy.ShangPinId=26

 

优化使用临时表:

select a.* into #temp from( select a.userid, min(a.LastLoginTM) as FirstLoginTime, max(a.LastLoginTM) as LastLoginTime from TLoginRecord a,
TUsers b where a.UserID=b.UserID and b.IsRobot=0 and 
a.LastLoginTM>='2018-01-17 00:00:00' and a.LastLoginTM<='2018-01-17 23:59:59' group by a.userid) a

select b.* into #temp2 from(
select count(*) as GameCount,isnull(sum(GameTime),0)/60 as OnlineTime,UserID from TChangeRecord t1 inner join TChangeRecordUser t2 on 
t1.ID=t2.RecordIndex and EndTime>='2018-01-17 00:00:00' and EndTime<='2018-01-17 23:59:59' group by UserID)b

select c.* into #temp3 from(
select Users_ids as userid,SUM(PayMoney) as TotalPayMoney from Web_RMBCost where PaySuccess=1 
and addtime>='2018-01-17 00:00:00' and addtime<='2018-01-17 23:59:59' group by Users_ids)c

select '2018-02-26' as Reportdate, tp.*,tu.NickName,tf.superid,ISnull(ta.OnlineTime,0) OnlineTime,
Isnull(ta.GameCount,0) GameCount ,ISnull(tb.TotalPayMoney,0) TotalPayMoney,
sy.ShuLiang as ShuLiang from #temp tp left join TUsers tu on tp.userid=tu.UserID 
left join TUserInfo tf on tp.userid=tf.UserID 
left join #temp2 ta on tp.userid=ta.UserID 
left join #temp3 tb on tp.userid=tb.UserID 
left join Shop_YongHuShangPin sy on tp.userid=sy.Userid and sy.ShangPinId=26

  

 

转载于:https://www.cnblogs.com/xulanjun/p/8479930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值