[英]MYSQL query for getting daily data for last 30 days count even if data not exists for any date
I have table : "orders"(order_id,order_processed_date). 我有表格:“订单”(order_id,order_processed_date)。 I want count of orders per day for last 30 days. 我希望最近30天每天的订单数。 If any date has 0 orders, then it should print 0. 如果任何日期有0个订单,则应打印0。
Something like this: 像这样:
total | date
1 | 2018-10-20
0 | 2018-10-19
0 | 2018-10-18
0 | 2018-10-17
2 | 2018-10-16
0 | 2018-10-15
1 | 2018-10-14
0 | 2018-10-13
0 | 2018-10-12
1 | 2018-10-11
1 | 2018-10-10
5 | 2018-10-09
1 | 2018-10-08
and so on upto 2018-09-20. 依此类推,直到2018-09-20。 I already searched in stackoverflow and get some queries but did not find exact solution for this. 我已经在stackoverflow中进行了搜索,并得到了一些查询,但没有找到确切的解决方案。 I get result using below query but it has only records which date has not 0 orders: 我使用下面的查询获取结果,但它仅记录日期不为0的订单:
SELECT COUNT(order_id) AS total, DATE(order_processed_date) AS date
FROM orders
WHERE order_processed_date BETWEEN '2018-09-20' AND '2018-10-20'
GROUP BY DATE(order_processed_date)
ORDER BY order_processed_date DESC
Can please someone help me to give me result as I required. 可以请别人帮我给我所需的结果。
You could try to use a calendar table , an example of which is described here . 您可以尝试使用日历表 , 此处介绍了一个示例。 Basically, this is a table with an ordered list of dates (+ extra properties if you'd like). 基本上,这是一个有序排列的日期表(如果需要,可以添加其他属性)。
You could use the calendar table to LEFT JOIN
your orders
on, and use a GROUP BY
to get the results eg per month. 您可以使用日历表LEFT JOIN
您的orders
,并使用GROUP BY
获得结果,例如每月。
Best of luck. 祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.