如何使用SQL Query自动生成日期范围之间的日期?

问题描述 投票:0回答:1

我只想使用SQL Query生成数据范围之间的日期。

资源:

enter image description here

结果:

enter image description here

谢谢,劳伦斯A.

sql date date-range auto-generate
1个回答
1
投票

以下是使用计数表创建日历表的方法:

declare @source table
(
    user_id int not null primary key clustered,
    from_date date not null,
    to_date date not null
);

insert into @source
values
(1, '02/20/2019', '02/23/2019'),
(2, '02/22/2019', '02/28/2019'),
(3, '03/01/2019', '03/05/2019');

with
rows as
(
    select top 1000
    n = 1
    from sys.messages
),
tally as
(
    select n = row_number() over(order by (select null)) - 1
    from rows
),
calendar as
(
    select
    date = dateadd(dd, n, (select min(from_date) from @source))
    from tally
)
select
s.user_id,
c.date
from @source s
cross join calendar c
where c.date between s.from_date and s.to_date;

结果集: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.