我有一个像这样的mysql查询....
SELECT CAST(created_at AS DATE) as 'Created_Date', DAYNAME(CAST(created_at AS DATE)) as 'Day', sum(order_type_id=1) as 'Pickup', sum(order_type_id=2) as 'Delivery'
FROM orders
WHERE created_at >= curdate() - INTERVAL 7 DAY
AND created_at < curdate()
AND order_status_id != 3
group by CAST(created_at AS DATE);
返回一些数据,如下所示
Date | Day | Pickup | Delivery
-----------------------------------------------
2017-08-08 | Tuesday | 02 | 01
2017-08-09 | Wednesday | 01 | 01
2017-08-10 | Thursday | 01 | 00
2017-08-11 | Friday | 01 | 01
2017-08-13 | Sunday | 01 | 00
2017-08-14 | Monday | 01 | 01
我想要做的是在过去的7天内除了今天之前得到一些交货单和取货单的总结。
我的问题:如果您仔细观察上述情况,您会注意到我在2017-08-12(星期六)没有输出,因为在同一天没有完成任何操作。知道如何将这些空日期输入到我的输出中,所以我有类似下面的内容????
Date | Day | Pickup | Delivery
-----------------------------------------------
2017-08-08 | Tuesday | 02 | 01
2017-08-09 | Wednesday | 01 | 01
2017-08-10 | Thursday | 01 | 00
2017-08-11 | Friday | 01 | 01
2017-08-12 | Saturday | 00 | 00
2017-08-13 | Sunday | 01 | 00
2017-08-14 | Monday | 01 | 01
答案 0 :(得分:0)
如果您确实拥有所有日期的数据(只是在该日期没有您想要的状态),那么您可以使用条件聚合:
select CAST(created_at AS DATE) as Created_Date,
DAYNAME(CAST(created_at AS DATE)) as Day,
sum(order_type_id = 1 and order_status_id <> 3) as Pickup,
sum(order_type_id = 2 and order_status_id <> 3) as Delivery
from orders
where created_at >= curdate() - INTERVAL 7 DAY AND created_at < curdate()
group by CAST(created_at AS DATE);
如果不是这种情况,那么您需要一个每个日期都有一行的表。最简单的方法是日历表。
答案 1 :(得分:0)
你可以尝试用你喜欢的方式加入你的选择。
RIGHT JOIN (
select curdate() as `date` union
select DATE_SUB(curdate(), INTERVAL 1 day) as `date` union
select DATE_SUB(curdate(), INTERVAL 2 day) as `date` union
select DATE_SUB(curdate(), INTERVAL 3 day) as `date` union
select DATE_SUB(curdate(), INTERVAL 4 day) as `date` union
select DATE_SUB(curdate(), INTERVAL 5 day) as `date` union
select DATE_SUB(curdate(), INTERVAL 6 day) as `date`
) as dates