SQL显示空值组

时间:2017-05-14 16:22:15

标签: mysql 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组,但是如果有null则不显示

1 个答案:

答案 0 :(得分:0)

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