2017-05-14 22 views
1

這是表在我的數據庫SQL顯示空值組通過

+--+-------+---------+----------+--------+ 
|ID|OrderID|ProductID|OrderDate |Quantity| 
| 1|1  |1  |2017-01-01|1  | 
| 2|1  |1  |2017-01-01|6  | 
| 3|1  |1  |2017-01-03|9  | 
| 4|1  |1  |2017-01-04|3  | 
| 5|1  |1  |2017-01-05|5  | 
| 6|1  |1  |2017-01-07|1  | 
| 7|1  |1  |2017-01-09|2  | 
+--+-------+---------+----------+--------+ 

我想說明這樣

+----------+----+ 
|2017-01-01|7 | 
|2017-01-02|0 | 
|2017-01-03|9 | 
|2017-01-04|3 | 
|2017-01-05|5 | 
|2017-01-06|0 | 
|2017-01-07|1 | 
|2017-01-08|0 | 
|2017-01-09|2 | 
+----------+----+ 

什麼查詢我應該使用有可能的數據,我已經試圖通過OrderDate使用組,但是當它爲空時,它不顯示

+3

你需要一個日期表來做到這一點。你的數據庫中有這樣的表嗎? –

+0

有沒有其他的解決方案沒有創建日期表? – madiluzi

+0

「*有空時*」是什麼意思? – melpomene

回答

1

在給定日期範圍之間生成日期的一種方法是給出this答案。

您可以即時生成行或更好地創建日曆表並將其用於此目的。

這裏是基於上述聯溶液的溶液:

select d.day, sum(t.quantity) as quantity 
from (
    select min_orderdate + INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date 
    from (
     select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 
     ) as a 
    cross join (
     select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 
     ) as b 
    cross join (
     select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 
     ) as c 
    join (
     select min(orderdate) min_orderdate, max(orderdate) max_orderdate from your_table 
     ) t on min_orderdate + INTERVAL (a.a + (10 * b.a) + (100 * c.a)) <= max_orderdate 
    ) d 
left join your_table t on d.day = t.orderdate 
group by d.day; 

這裏是相同的Demo