这是我的sql
select count(type), type
from tasks
group by type
这里有 4 行。
count(type) type
8 Trial
7 New
3 Service
4 Uninstall
如何在返回中得到一行结果
Trial New Service Uninstall
8 7 3 4
我知道它必须自连接表。但是我无法准确地得到。
这是示例表数据
id type date
1 New 2017-10-07
2 Trial 2017-10-01
3 New 2017-10-02
4 Uninstall 2017-10-05
5 Trial 2017-10-06
6 Trial 2017-10-07
最佳答案
这是通过条件聚合完成的:
select
sum(type = 'Trial') as trial,
sum(type = 'New') as new,
sum(type = 'Service') as service,
sum(type = 'Uninstall') as uninstall
from mytable;
在 MySQL 中 true 为 1,false 为 0,因此我们可以使用 SUM
来计算匹配。
关于mysql - 我按类型分组并计数自连接表以获取摘要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47139922/