简体   繁体   English

SQL Server - 递归 DATEADD 查询

[英]SQL Server - recursive DATEADD query

How do I get the following query give me the same date for the last N years?如何获得以下查询给我过去 N 年的相同日期?

declare @step int = 0;
declare @datobserve date = '2021-11-03';

with dates as 
(
select dateadd(year, @step, @datobserve) datobserve, @step step
union all
select dateadd(year, step, datobserve) as datobserve, step - 1
from dates
where 1=1
--and step = step + 1
and step > -4
)
select * from dates

The result I am getting is:我得到的结果是:

在此处输入图片说明

instead of:代替:

在此处输入图片说明

You need to make two changes in the recursive member of your statement:您需要在语句的递归成员中进行两项更改:

  • Use @datobserve instead of datobserve使用@datobserve代替datobserve
  • Use step - 1 instead of step使用step - 1而不是step
declare @step int = 0;
declare @datobserve date = '2021-11-03';

with dates as 
(
   select dateadd(year, @step, @datobserve) datobserve, @step step
   union all
   select dateadd(year, step - 1, @datobserve) as datobserve, step - 1
   from dates
   where step > -4
)
select * 
from dates

Result:结果:

datobserve  step
2021-11-03  0
2020-11-03  -1
2019-11-03  -2
2018-11-03  -3
2017-11-03  -4

Just another option using an ad-hoc tally table使用临时计数表的另一种选择

Example例子

Declare @Years int = 4
Declare @Date date ='2021-11-03'

Select dateobserve = dateadd(year,N,@Date)
      ,Step = N
 From ( Select Top (@Years+1) N=1-Row_Number() Over (Order By (Select NULL)) 
          From master..spt_values n1
      ) NT

Results结果

dateobserve Step
2021-11-03  0
2020-11-03  -1
2019-11-03  -2
2018-11-03  -3
2017-11-03  -4

When you know it's only a handful of rows, like 5, I find it simpler to not bother with recursion:当你知道它只有几行时,比如 5,我发现不打扰递归更简单:

DECLARE @datobserve date = '20211103';

;WITH n(n) AS 
(
  SELECT n FROM (VALUES(1),(2),(3),(4),(5)) AS n(n)
)
SELECT datobserve = DATEADD(YEAR, 1-n, @datobserve), step = 1-n 
FROM n
ORDER BY datobserve DESC;

If the list is larger or variable, I still like to get the numbers part recursively, and work the dates around that output:如果列表更大或可变,我仍然喜欢递归地获取数字部分,并围绕该输出处理日期:

DECLARE @steps      int  = 5,
        @datobserve date = '20211103';

;WITH n(n) AS 
(
  SELECT 1 UNION ALL SELECT n+1 FROM n WHERE n < @steps
)
SELECT datobserve = DATEADD(YEAR, 1-n, @datobserve), step = 1-n 
FROM n
ORDER BY datobserve DESC;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM