SQL Server 使用T-SQL从日期范围中获取单个日期

hfwmuf9z  于 2023-02-03  发布在  其他
关注(0)|答案(2)|浏览(153)

我被要求创建两个数据集,显示来自两个日期范围的7天日期。
例如:我有一个日期范围StartDate = 2022-12-12EndDate = 2022-12-25。我需要一个查询来显示这两个日期之间的各个日期。我被告知使用DATEADD,但无法为生活搞清楚这一点。
任何帮助都会很有帮助,谢谢。

SELECT DATEADD(DAY, 7, StartDate) AS WeekOne

我就知道会这样:

2022-12-12
2022-12-13
2022-12-14
2022-12-15
2022-12-16
2022-12-17
2022-12-18
34gzjxbg

34gzjxbg1#

DECLARE @InStartDate DATE='2022-12-12';
DECLARE @InStopDate DATE='2022-12-25';
WITH GEN AS
(
   SELECT @InStartDate AS Start_dated
      UNION ALL
   SELECT DATEADD(DD,1,G.Start_dated)
     FROM GEN AS G
   WHERE G.Start_dated< @InStopDate
)
SELECT G.*
FROM GEN AS G

你可以用这个

6rqinv9w

6rqinv9w2#

你需要从生成一个数字表开始,它需要足够的行来处理开始日期和结束日期之间的每一天,比如:

with Numbers as (
    select 0 as n
    union all
    select n + 1
    from Numbers
    where n < 365
)
select n
from Numbers
option(maxrecursion 0);

给定示例范围后,我觉得365天(一年)就足够了,但调整这个范围很容易(我们将看到)。
有了Numbers表后,可以使用DateAdd()将该金额添加到开始日期:

DECLARE @StartDate date = '20221212'; 

with Numbers as (
    select 0 as n
    union all
    select n + 1
    from Numbers
    where n < 365
)
select DATEADD(day, n, @StartDate)
from Numbers
option(maxrecursion 0)

从这里开始,在WHERE子句中使用EndDate来限制总行数就很简单了:

DECLARE @StartDate date = '20221212'; 
DECLARE @EndDate date = '20221231';

with Numbers as (
    select 0 as n
    union all
    select n + 1
    from Numbers
    where n < DATEDIFF(day, @StartDate, @EndDate)
)
select DATEADD(day, n, @StartDate)
from Numbers
option(maxrecursion 0)

相关问题