簡體   English   中英

如何在多個記錄上使用CTE

[英]How to use a CTE on multiple records

我有一個這樣的日期表:

Exit_Date     Date_ID
2017-05-31     1
2017-04-26     2
2017-01-02     3
2016-12-24     4
2016-11-27     5

我使用循環將每個這些日期插入CTE以生成這些日期的最后15年,如下所示:

declare @DI int = 1
declare @d date
while @DI <=5
begin
select @d = Exit_Date from Date_Table where Date_ID = @DI
declare @EDTable table (Exit_Date  Date);
with
  a as(
    select dateadd(yy,-1,@d) d,0 i
      union all
    select dateadd(yy,-1,d),i+1 from a where i<14
  ),
  b as(select d,datediff(dd,0,d)%7 dd from a)
 insert into @EDTable select d from b;
  set @DI = @DI + 1
 end

結果是正確的,我的日期有75行。 我想知道是否有一種方法可以通過用@d的每個日期記錄替換變量@d來擺脫WHILE循環?

您可以將循環替換為數字表或即席數字表,如下所示:

;with numbers as (
  select top (15)
    i = row_number() over (order by (select 1))
  from [master]..spt_values
)
select Exit_Date = dateadd(year,-1*i,d.Exit_Date)
from Date_Table d
  cross join numbers n
where d.Date_id >= 1
  and d.Date_id <= 5

extrester演示: http ://rextester.com/AQEZ43941


此方法的性能優於遞歸解決方案,尤其是當行數增加時。

參考:

只需使用遞歸CTE中的表即可:

create table #DateTable (
    Date_ID int primary key not null,
    Exit_Date date not null
);

insert into #DateTable (Exit_Date, Date_ID) values
('2017-05-31',1),
('2017-04-26',2),
('2017-01-02',3),
('2016-12-24',4),
('2016-11-27',5);

declare @EDTable table (Exit_Date  Date);

;with a as (
    select dateadd(yy,-1,Exit_Date) d,0 i from #DateTable where Date_ID between 1 and 5
    union all
    select dateadd(yy,-1,d),i+1 from a where i<14
)
,b as (
    select d,datediff(dd,0,d)%7 dd from a
)
insert into @EDTable
select d from b;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM