当前位置: 代码迷 >> Sql Server >> 请问这句SQL应该如何优化呢
  详细解决方案

请问这句SQL应该如何优化呢

热度:29   发布时间:2016-04-27 14:51:43.0
请教这句SQL应该怎么优化呢?
SQL code
if object_id('tempdb..#tb') is not null   drop table #tbgocreate table #tb( datev datetime,--统计日期 gameid int,--游戏ID coin int,--获得金币 userid int--会员ID)goinsert into #tbselect '2011-12-20',1,100,1 union allselect '2011-12-20',2,100,1 union allselect '2011-12-20',1,-100,2 union allselect '2011-12-20',1,100,3 union allselect '2011-12-20',2,-200,3 union allselect '2011-12-21',2,100,1 union allselect '2011-12-21',1,500,2 union allselect '2011-12-21',2,-200,3go--目的是统计出某时段内所有游戏获得金币总和的排行,条件是当日所有游戏获得金币的总和小于0则不参与排行--这是我目前用的,但很慢,数据只有60W条左右declare @date1 datetime,@date2 datetimeset @date1='2011-12-1'set @date2='2011-12-30' select top 100 userid,sum(ct) as ctA from (select userid,sum(coin) as ct,datev from #tb with(nolock) where userid not in(5,6,7,10,21...这里偶尔会手动添加些不参与排行的会员ID) and datev>[email protected] and datev<[email protected] group by userid,datev HAVING sum(coin)>0)  as uctgroup by userid order by ctA desc




------解决方案--------------------
userid
datev
有没有建立索引
------解决方案--------------------
try:
SQL code
select datev,userid,sum(coin)ct into #from #tb where userid not in(5,6,7,10,21) and datev>[email protected] and datev<[email protected] group by datev,userid having sum(coin)>0select top 100 userid,sum(ct) as ctA from # group by userid order by 2 desc
------解决方案--------------------
探讨
SQL code


if object_id('tempdb..#tb') is not null
drop table #tb
go
create table #tb
(
datev datetime,--统计日期
gameid int,--游戏ID
coin int,--获得金币
userid int--会员ID
)
go

insert into……
  相关解决方案