SQL Count to include zero values

前端 未结 4 2156
太阳男子
太阳男子 2020-12-19 08:59

I have created the following stored procedure that is used to count the number of records per day between a specific range for a selected location:

[dbo].[ge         


        
4条回答
  •  轮回少年
    2020-12-19 09:26

    When there is no data to count, there is no row to return.

    If you want to include empty days as a 0, you need to create a table (or temporary table, or subquery) to store the days, and left join to your query from that.

    eg: something like

    SELECT 
        COUNT(*) AS counted_leads,  
        CONVERT(VARCHAR, DATEADD(dd, 0, DATEDIFF(dd, 0, Time_Stamp)), 3) as TIME_STAMP  
        FROM 
            TableOfDays
               left join
            HL_Logs 
               on TableOfDays.Date = convert(date,HL_Logs.Time_Stamp)
               and ID_Location = @LOCATION 
        WHERE TableOfDays.Date between @BEGIN and @END 
        GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, Time_Stamp)) 
    

提交回复
热议问题