Show data from table even if there is no data!! Oracle

后端 未结 3 1771
悲&欢浪女
悲&欢浪女 2021-01-25 05:34

I have a query which shows count of messages received based on dates. For Eg:

1 | 1-May-2012 
3 | 3-May-2012 
4 | 6-May-2012 
7 | 7-May-2012 
9 | 9-May-2012 
5 |         


        
3条回答
  •  甜味超标
    2021-01-25 05:37

    You could achieve this with a left outer join IF you had another table to join to that contains all possible dates.

    One option might be to generate the dates in a temp table and join that to your query.

    Something like this might do the trick.

    CREATE TABLE #TempA (Col1 DateTime)
    DECLARE @start DATETIME = convert(datetime, convert(nvarchar(10), getdate(), 121))
    SELECT @start
    
    DECLARE @counter INT = 0
    
    WHILE @counter < 50
    BEGIN
        INSERT INTO #TempA (Col1) VALUES (@start)
        SET @start = DATEADD(DAY, 1, @start)
        SET @counter = @counter+1
    END
    

    That will create a TempTable to hold the dates... I've just generated 50 of them starting from today.

    SELECT 
        a.Col1,
        COUNT(b.MessageID)
    FROM
        TempA a
        LEFT OUTER JOIN YOUR_MESSAGE_TABLE b
            ON a.Col1 = b.DateColumn
    GROUP BY
        a.Col1
    

    Then you can left join your message counts to that.

提交回复
热议问题