我有一个按天分组的付款表
select
day(created),
sum(payments.amount)
from payments
group by day(created)
输出
day | amount
1 | 432
2 | 4567
5 | 345
6 | 2345
7 | 97
这很好,但我想在没有付款的日子里添加一些0
。
预期输出:
day | amount
1 | 432
2 | 4567
3 | 0
4 | 0
5 | 345
6 | 2345
7 | 97
最佳答案
由于您在付款
表中没有所有日期,您可以执行以下操作:
select
d,
ifnull(sum(p.amount),0) sum_amount
from (
select 1 as d
union all
select 2
union all
select 3
union all
select 4
union all
select 5
union all
select 6
union all
select 7
) d
left join payments p
on day(p.created) = d.d
group by d
order by d
关于如果没有结果,mysql选择日期的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42308498/