我有一张桌子订单:
id total_amount date_order
1 12.000 2018-09-01
2 10.000 2018-09-01
3 5.000 2018-09-03
4 2.000 2018-09-05
我有按日期查询SUM数据组:
select SUM(total_amount) as 'total', DATE(date_order) as 'date'
from Order
where date_order >= '2018-09-01' and date_order <= '2018-09-06'
group by (date_order)
它显示:
total date
22.000 2018-09-01
5.000 2018-09-03
2.000 2018-09-05
因为 2018-09-02 和 2018-09-04 中的数据均无数据,因此未在结果中显示。但我想查询显示具有预期结果的表:
total date
22.000 2018-09-01
0 2018-09-02
5.000 2018-09-03
0 2018-09-04
2.000 2018-09-05
每个人都可以帮助我编写查询以显示预期结果吗?
答案 0 :(得分:2)
创建另一个要联接的表。
它可能是日期表,例如2000年1月1日至2099年12月31日之间的所有日期...
SELECT
dt.`date`,
SUM(total_amount) as `total`
FROM
yourDatesTable AS dt
LEFT JOIN
Order AS o
ON o.`date_order` = dt.`date`
WHERE
dt.`date` >= '2018-09-01'
AND dt.`date` < '2018-09-08'
GROUP BY
dt.`date`
ORDER BY
dt.`date`
或者它可能是一个数值表,其值介于-1023到+1024 (或其他有用范围) ...
SELECT
n.id,
'2018-09-01' + INTERVAL n.id DAYS,
SUM(total_amount) as `total`
FROM
yourNumbersTable AS n
LEFT JOIN
Order AS o
ON o.`date_order` = '2018-09-01' + INTERVAL n.id DAYS
WHERE
n.id >= 0
AND n.id < 8
GROUP BY
n.id
ORDER BY
n.id
答案 1 :(得分:1)
生成日期并与订单表联接
select SUM(O.total_amount) as total, DATE(gen_date) as oreder_date
from
(
select * from
(select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) gen_date from
(select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where gen_date between '2018-09-01' and '2018-09-30'
) as t1 left join `Order` O on t1.gen_date= DATE(O.date_order)
where gen_date >= '2018-09-01' and gen_date <= '2018-09-06'
group by oreder_date