SQL Date Query include month even if no data

前端 未结 2 1052
旧巷少年郎
旧巷少年郎 2021-01-28 04:38

I have a booking database with various dates for each booking. I want to get a count of all bookings in each month e.g.

JAN | 12
FEB | 15
MAR | 53
APR | 25
         


        
2条回答
  •  深忆病人
    2021-01-28 04:52

    You need to have a table variable with all the months and do a JOIN.

    DECLARE @months TABLE (MonthNumber INT, YearNumber INT, Name VARCHAR(50))
    
    INSERT INTO @months (MonthNumber, YearNumber, Name) VALUES (1, 2015, 'January')
    ...
    
    
    SELECT MonthNumber, YearNumber, ISNULL(SUM(...), 0)
    FROM Booking b
    RIGHT JOIN @months mo ON DATEPART(m, b.BookingDate)=mo.MonthNumber AND DATEPART(yy, b.BookingDate)=mo.YearNumber
    GROUP BY mo.MonthNumber, mo.YearNumber
    

    EDIT: If you want to consider multiple years, add year as a column in @month and change the CROSS JOIN condition to consider month and year.

提交回复
热议问题