我的销售表
ID amount created_at
48 10 2018-10-15 10:57:24
49 20 2018-10-16 10:58:14
50 25 2018-10-22 14:07:31
51 24 2018-10-24 12:13:15
52 36 2018-10-24 12:13:21
53 40 2018-10-30 09:46:37
54 40 2018-10-28 09:46:37
55 40 2018-11-1 09:46:37
56 40 2018-11-2 09:46:37
57 40 2018-11-2 09:46:37
58 40 2018-11-2 09:46:37
59 40 2018-11-2 09:46:37
60 40 2018-11-2 09:46:37
我的qyery
SELECT Date(created_at),
Count(*)
FROM sale
WHERE Date(created_at) BETWEEN ( Now() - INTERVAL 7 day ) AND Now()
GROUP BY Date(created_at)
我的结果
date(created_at) count
2018-10-28 12:13:15 1
2018-10-1 09:46:37 1
2018-10-2 09:46:37 5
假设周从2018-10-28开始,如果没有特定日期的记录,则需要以下结果,则它将为0。
day count
mon 1
tue 0
wed 0
thu 1
fri 5
sat 0
sun 0
答案 0 :(得分:2)
%a
指定符一起使用,以获取特定日期created_at
的缩写工作日名称。我们可以将其用作我们的Left Join
条件。Left Join
使我们可以考虑所有工作日,即使在特定的一天没有匹配的created_at
。Count(*)
在这里不起作用,因为它会计算组中的所有行。但是,我们不想对没有匹配行的行进行计数。因此,我们使用Count(created_at)
,因为它将忽略null
的值。Date()
子句中的Where
函数用法来进行Date_format()
查询。您需要在工作日使用主表。
查询:
SELECT week_table.day_order,
week_table.wkday AS `day`,
Count(created_at) AS `count`
FROM
(
SELECT 'Mon' AS wkday, 1 AS day_order UNION ALL
SELECT 'Tue', 2 UNION ALL
SELECT 'Wed', 3 UNION ALL
SELECT 'Thu', 4 UNION ALL
SELECT 'Fri', 5 UNION ALL
SELECT 'Sat', 6 UNION ALL
SELECT 'Sun', 7
) AS week_table
LEFT JOIN sale AS s
ON DATE_FORMAT(created_at, '%a') = week_table.wkday AND
created_at >= ( CURDATE() - INTERVAL 7 day ) AND
created_at < ( CURDATE() + INTERVAL 1 day )
GROUP BY week_table.day_order, week_table.wkday
ORDER BY week_table.day_order;
结果
| day_order | day | count |
| --------- | --- | ----- |
| 1 | Mon | 0 |
| 2 | Tue | 1 |
| 3 | Wed | 0 |
| 4 | Thu | 1 |
| 5 | Fri | 5 |
| 6 | Sat | 0 |
| 7 | Sun | 1 |