SQL Date Query include month even if no data

纵饮孤独 提交于 2019-12-02 08:56:27

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.

Juan Carlos Oropeza

The easy way is using a months table because you can have empty months.

create table months (
   month_id integer,
   date_ini datetime,
   date_end datetime
) 

And this are some examples of how create that table automatic

Using select Generate days from date range

This use store procedure in MSQL

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!