答案 0 :(得分:0)
尝试以下查询:
首先我们需要使用CalendarData
或sys.all_objects
动态生成[master]..spt_values
,如下所示:
DECLARE @MinDate DATE = '2017-01-01',
@MaxDate DATE = '2017-12-31';
SELECT TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate) as CalendarDate
FROM
sys.all_objects a
CROSS JOIN
sys.all_objects b;
有关详细信息,请查看此链接https://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-2
所以完整的解决方案可能就像
DECLARE @MinDate DATE = '2017-01-01',
@MaxDate DATE = '2017-12-31';
WITH calendareDates AS
(
SELECT TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.number) - 1, @MinDate) AS CalendarDate
FROM
[master]..spt_values a
--CROSS JOIN [master]..spt_values b -- use this cross join to get more records only if your dates between Start and End Date are over years.
)
SELECT
ROW_NUMBER() OVER (ORDER BY CalendarDate) id,
c.CalendarDate, e.eventTitle, e.eventId
FROM
Events e
LEFT JOIN
calendareDates c ON c.CalendarDate BETWEEN e.StartDate AND e.EndDate