用于开始日期和时间的SQL查询记录之间的结束日期范围

时间:2017-08-22 04:46:12

标签: sql sql-server-2008

我的数据库结构如下:

enter image description here

和输出如下:

enter image description here

那么,如何进行SQL查询?

1 个答案:

答案 0 :(得分:0)

尝试以下查询:

首先我们需要使用CalendarDatasys.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