我想获得特定日期的每小时销售数量:
table : invoices
+-------+-----------+-----------+--------------------------+
| id | name | amout | date |
+-------+-----------+-----------+--------------------------+
| 1 | John | 12313 | 2017-05-20 13:50:08 |
| 2 | Mary | 5335 | 2017-05-17 22:21:35 |
| 3 | Jeff | 23 | 2017-05-17 22:32:13 |
| 4 | Bill | 132 | 2017-05-17 23:25:55 |
| 5 | Bob | 853 | 2017-05-17 24:52:37 |
+-------+-----------+-----------+--------------------------+
所以,我想得到这个输出:
9 a.m. to 10 a.m. we generated X invoices.
10 a.m. to 11 a.m. we generated Y invoices.
11 a.m. to 12 a.m. we generated Z invoices.
我怎么能这样做?我使用MySQL。
谢谢!
答案 0 :(得分:0)
三个SQL概念将帮助您获得此问题的答案。
2017-05-27 14:37.20
被截断为2017-05-27 14:00:00
。COUNT(*)
和GROUP BY
。你可以像这样截断。
SELECT DATE_FORMAT(`date`, '%y-%m-%d %H:00:00') hour_starting
FROM invoices
您可以添加到该查询以选择特定日期的行,例如
SELECT DATE_FORMAT(`date`, '%y-%m-%d %H:00:00') hour_starting
FROM invoices
WHERE `date` >= '2017-05-27`
AND `date` < '2017-05-27' + INTERVAL 1 DAY
请注意,这会选择>=
午夜(2017-05-27
)午夜或之后的所有行。之前但不包括(<
)第二天午夜。
最后,您可以像这样使用COUNT。
SELECT DATE_FORMAT(`date`, '%y-%m-%d %H:00:00') hour_starting,
COUNT(*) invoice_count
FROM invoices
WHERE `date` >= '2017-05-27`
AND `date` < '2017-05-27' + INTERVAL 1 DAY
GROUP BY DATE_FORMAT(`date`, '%y-%m-%d %H:00:00')