If object_id ('pubs .. tb') is not null
Drop table TB
Go
Create Table TB
(
Noteid varchar (10 ),
Saledate datetime
)
Insert into Tb (noteid, saledate) values ('v1 ', '2017-09-12 ')
Insert into Tb (noteid, saledate) values ('v2', '2017-09-12 ')
Insert into Tb (noteid, saledate) values ('v3 ', '2017-09-12 ')
Insert into Tb (noteid, saledate) values ('v4 ', '2017-08-12 ')
Go
If object_id ('pubs .. mymonths') is not null
Drop table mymonths
Go
Create Table mymonths
(
Mymonths varchar (7)
)
Declare @ dt1 as datetime
Declare @ dt2 as datetime
Set @ dt1 = '2017-07-01 '-- Start Time
Set @ dt2 = '2017-10-01 '-- End Time
Declare @ I as int
Set @ I = 1
Declare @ CNT as int -- number of months
Set @ CNT = (Year (@ dt2)-year (@ dt1) * 12 + (month (@ dt2)-month (@ dt1) + 1)
While @ I <= @ CNT
Begin
Insert into mymonths values (convert (varchar (7), @ dt1, 120 ))
Set @ dt1 = dateadd (month, 1, @ dt1)
Set @ I = @ I + 1
End
Select M. mymonths as month, isnull (N. quantity, 0) as quantity from mymonths m
Left join
(Select convert (varchar (7), saledate, 120) as saledate, count (*) as quantity from TB group by convert (varchar (7), saledate, 120) N
On M. mymonths = n. saledate
Drop table TB, mymonths
Number of months
------------------
2005-07 0
2005-08 1
2005-09 3
2005-10 0
2005-11 0
2005-12 0
2006-01 0
2006-02 0
2006-03 0
2006-04 0
2006-05 0
2006-06 0
2006-07 0
2006-08 0
2006-09 0
2006-10 0
(The number of affected rows is 16)