The problem of monthly statistics, that is, the data for the month does not exist, and the data for the month is displayed as 0

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.