简体   繁体   中英

SQL Query for start date & end date range between record

i have database structured like this:

在此处输入图片说明

and Output like this:

在此处输入图片说明

so, how to make SQL Query?

Try the following query:

first we need to generate CalendarData on the fly using sys.all_objects or [master]..spt_values as shown here:

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;

For more information check this link https://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-2

So the full solution might be like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM