Data that is not in the SQL time period equals 0

Source: Internet
Author: User

How to implement a no time period in the use of the zeros fill??

if object_id('[A]') is  not NULL Drop Table [A]Go Create Table [A]([Date] datetime,[Amount] int)Insert [A]Select *  from [A]Select '2014-05-01', - Union  AllSelect '2014-05-02', $ Union  AllSelect '2014-05-05', - Union  AllSelect '2014-05-06', $Declare @stdate smalldatetime,        @eddate smalldatetimeSelect  @stdate=min([Date]),        @eddate=Max([Date]) from [A]; withSel as( Select @stdate  as [Date],1  asValUnion  All Select  DateAdd( Day, Val,@stdate), Val+1  asVal fromSelwhereVal<=DateDiff( Day,@stdate,@eddate))SelectSel.[Date]  as [Date],sum(IsNullA.[Amount],0)) as [Amount]  fromsel Left Join [A]  onSel.[Date]=[A].[Date] Group  bySel.[Date]

Explain: With this step is key, through which it makes "select DATEADD (Day,val, @stdate), val+1 as Val from Sel where Val<=datediff (day, @stdate, @ Eddate) "has been querying the time difference

Then associate through an outer link

Data that is not in the SQL time period equals 0

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.