SQL Count to include zero values

前端 未结 4 2163
太阳男子
太阳男子 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:15

    I just recently has a similar task and used this as a backdrop to my work. However, as explained by robwilliams I too, couldn't get it KeithS solution to work. Mine task was slightly different I was doing it by hours vs days but I think the solution to the neilrudds question would be

    DECLARE @Start as DATETIME
           ,@End as DATETIME
           ,@LOCATION AS INT;
    
    
    WITH CTE_Dates AS
    (
        SELECT @Start AS cte_date, 0 as 'counted_leads'
        UNION ALL
        SELECT DATEADD(DAY, 1, cte_date) as cte_date, 0 AS 'counted_leads'
        FROM CTE_Dates  
        WHERE DATEADD(DAY, 1, cte_date) <= @End
    )
    SELECT cte_date AS 'TIME_STAMP'
          ,COUNT(HL.ID_Location) AS 'counted_leads'
    FROM CTE_Dates 
    LEFT JOIN HL_Logs AS HL ON CAST(HL.Time_Stamp as date) = CAST(cte_date as date)
    AND DATEPART(day, HL.Time_Stamp) = DATEPART(day,cte_date)
    AND HL.ID_Location = @LOCATION
    group by cte_date
    OPTION (MAXRECURSION 0)
    

提交回复
热议问题