如何在MySQL中按工作日将总和分组?
作者:互联网
我有一张这样的桌子:
id | timestamp | type
-----------------------
1 2010-11-20 A
2 2010-11-20 A
3 2010-11-20 B
4 2010-11-21 A
5 2010-11-21 C
6 2010-11-27 B
我需要计算按工作日分组的每种类型的行;像这样:
weekday | A | B | C
--------------------------
5 2 2 0 -- the B column equals 2 because nov 20 and nov 27 are saturday
6 1 0 1
最简单的解决方案是什么?
我不介意使用视图,变量,子查询等.
解决方法:
采用:
SELECT WEEKDAY(t.timestamp) AS weekday,
SUM(CASE WHEN t.type = 'A' THEN 1 ELSE 0 END) AS a,
SUM(CASE WHEN t.type = 'B' THEN 1 ELSE 0 END) AS b,
SUM(CASE WHEN t.type = 'C' THEN 1 ELSE 0 END) AS c
FROM YOUR_TABLE t
GROUP BY WEEKDAY(t.timestamp)
标签:aggregate-functions,sql,mysql 来源: https://codeday.me/bug/20191023/1914834.html