我有这个简单的查询,可以获取2个日期之间的所有已完成订单(一次约6个月):
select IFNULL(sum(o.amount), 0) as amount, o.completed_at
from orders o
where date(o.completed_at) between '2011/10/01' and '2012/03/06'
group by year(o.completed_at), month(o.completed_at) order by o.completed_at
但这里的问题是例如在1月和2月,如果没有订单,那么这将只返回4行而不是6行6个月。
我需要它仍然返回6行,并为缺少的日期将数量设置为0。
以下是仅返回5行的示例输出 - 缺少3月我需要它出现:http://d.pr/DEuR
答案 0 :(得分:0)
尝试使用coalesce函数,如果sum(orders.amount)
在特定月份为空,则返回“0”:
select COALESCE(sum(o.amount), 0) as amount, o.completed_at
from orders o
where date(o.completed_at) between '2011/10/01' and '2012/03/06'
group by year(o.completed_at), month(o.completed_at) order by o.completed_at
答案 1 :(得分:0)
以下是您的需求:
1]创建辅助表
create table db.myDates(
completed_at date not null
)
2]用表中的月份填写表格,例如:
insert into db.myDates values('2011-10-01'),
('2011-11-01'),
('2011-12-01'),
('2012-01-01'),
('2012-02-01'),
('2012-03-01');
3]然后选择:
select a.completed_at, sum(b.amount)
from myDates a
left join orders b
on extract(year_month from a.completed_at)=extract(year_month from b.completed_at)
and date(b.completed_at) between '2012-01-05' and '2012-06-05'
group by year(b.completed_at)), month(dateCompleted)
order by a.completed_at;
结果看起来像这样(约会我的)
2012-01-01 27
2012-02-01 NULL
2012-03-01 47
2012-04-01 13
2012-05-01 12
2012-06-01 15
答案 2 :(得分:0)
由于许多因素,此查询很复杂。
最简单的解决方案可能是在每个月的第一天添加0金额。