需要帮助来优化T-SQL查询

时间:2014-04-23 16:15:59

标签: sql sql-server sql-server-2008 sql-server-2008-r2 query-optimization

以下是样本数据

DECLARE @maxval int, @minval int
select @maxval=201301,@minval=201312

SELECT top 100001 CAST(((@maxval + 1) - @minval) *
    RAND(CHECKSUM(NEWID())) + @minval AS int)Date ,ceiling (RAND(CHECKSUM(NEWID())) *1000+25692*RAND(CHECKSUM(NEWID()))  )*ceiling (RAND(CHECKSUM(NEWID())) *1000+25692*RAND(CHECKSUM(NEWID()))  )ID
into #sample from sysobjects , syscolumns

问题:

  • 有2列日期& ID
  • 取第一个月的身份证,例如201302
  • 需要在接下来的3个月内查找这些ID是否可用。所以这里是201303,201304,201305
  • 需要重复这几个月

这是我的代码,它需要更多的人工干预和时间。请协助。

select distinct   date from #sample order by DATE 

declare @processingdate varchar(6),@from varchar(6),@to varchar(6)
set @processingdate = '201302'
set @from = '201303'
set @to = '201305'


select distinct id into #Source from #sample where DATE = @processingdate
select distinct id into #lookup from #sample where DATE between @from and @to 

select @processingdate,count(*) from #Source where ID not in (select * from #lookup)

谢谢

1 个答案:

答案 0 :(得分:0)

试试这个:

select *
from #sample a
inner join #sample b
on a.ID = b.ID and a.Date IN (b.Date - 1, b.Date - 2, b.Date - 3)