SQL Server - show rows for missing dates

后端 未结 2 1520
孤城傲影
孤城傲影 2021-01-15 18:54

This is my SP in sql server 2008:

SELECT      
    CONVERT(NVARCHAR(30), YMD, 101) AS [DATE],               
    SUM(ISNULL(Jobs, 0)) AS [Jobs],     
    SUM         


        
相关标签:
2条回答
  • 2021-01-15 19:48

    I agree with @bluefeet approach

    in order to create a dynamic from-to calendar you can use a recursive cte like this one:

    DECLARE @DateFrom AS DATE
    DECLARE @DateTo as DATE 
    SET @DateFrom='7/23/2014'
    SET @DateTo ='7/29/2014'
    ;WITH r AS
    (SELECT @DateFrom AS calendardate
    UNION ALL
    SELECT DATEADD(d,1,calendardate) FROM r 
    WHERE DATEADD(d,1,calendardate)<=@DateTo
    ) 
    SELECT * FROM r
    
    0 讨论(0)
  • 2021-01-15 19:52

    @Jayvee's approach is great if you're using a fairly short span (up to about 100 on most configurations) but can break down if you use too many. If you find yourself in that situation, use a WHILE loop. And here's a full example in case the JOIN isn't clear. Note that you said you were in a stored procedure, my alternative won't work in a view but his will.

    DECLARE @DateFrom DATE
    DECLARE @DateTo DATE
    SET @DateFrom = '7/23/2014'
    SET  @DateTo = '7/29/2014'
    
    --BEGIN Add this
    DECLARE @X DATE
    DECLARE @D TABLE (EachDay Date)
    SET @X = @DateFrom
    WHILE @X <= @DateTo BEGIN
        INSERT INTO @D VALUES (@X)
        SET @X = DATEADD(day, 1, @X)
    END
    SELECT * FROM @D
    --END Add this
    
    SELECT      
        CONVERT(NVARCHAR(30), YMD, 101) AS [DATE],               
        SUM(ISNULL(Jobs, 0)) AS [Jobs],     
        SUM(ISNULL(SELL_VALUE, 0)) AS [COST]
        FROM    S       
            --ADD This - just the one following line
            RIGHT OUTER JOIN @D as D ON D.EachDay = S.YMD
        WHERE [YMD] BETWEEN @DateFrom AND @DateTo 
    GROUP BY YMD
    ORDER BY YMD DESC
    
    0 讨论(0)
提交回复
热议问题