1

以下是樣本數據,需要幫助優化T-SQL查詢

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
  • 拿第一個月的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) 

感謝

+2

你可以添加一些示例數據,以證明你想要的結果? – MatBailie

+2

有沒有可以利用的優勢? – gh9

回答

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) 
+0

工作正常。感謝您的查詢 – vignesh