I think I have a tough one here... :(
I am trying to get an order count by month, even when zero. Here\'s the problem query:
SELECT datename(month,
Here is one using recursive CTE:
declare @StartDate datetime = '2015-04-01';
declare @EndDate datetime = '2015-06-01';
-- sample data
declare @orders table (OrderNumber int, OrderDate datetime);
insert into @orders
select 11, '2015-04-02'
union all
select 12, '2015-04-03'
union all
select 13, '2015-05-03'
;
-- recursive CTE
with dates
as (
select @StartDate as reportMonth
union all
select dateadd(m, 1, reportMonth)
from dates
where reportMonth < @EndDate
)
select
reportMonth,
Count = count(o.OrderNumber)
from dates
left outer join @orders as o
on o.OrderDate >= reportMonth
and o.OrderDate < dateadd(MONTH, 1, reportMonth)
group by
reportMonth
option (maxrecursion 0);
;