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
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.
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