Как автоматически генерировать даты между диапазонами дат, используя SQL Query? - PullRequest
0 голосов
/ 11 марта 2019

Я просто хочу сгенерировать дату в диапазоне данных с помощью SQL-запроса.

Источник:

enter image description here

Результат:

enter image description here

Спасибо, Лоуренс А

1 Ответ

1 голос
/ 11 марта 2019

Вот как это сделать, используя таблицу подсчета для создания календарной таблицы:

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

...