[英]my group by type and count self joining table to get the summary
Here is my sql 这是我的sql
select count(type), type
from tasks
group by type
Here having 4 rows. 这里有4行。
count(type) type
8 Trial
7 New
3 Service
4 Uninstall
How do I get in one row result in return 我如何获得一行结果
Trial New Service Uninstall
8 7 3 4
I know it has to self-joining the table. 我知道它必须自动加入表格。 But I am not able to get exactly.
但是我无法完全得到。
Here is the sample table data 这是样本表数据
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 MAX(CASE WHEN type = 'Trial' THEN count_type END) as Trial,
MAX(CASE WHEN type = 'New' THEN count_type END) as New,
MAX(CASE WHEN type = 'Service' THEN count_type END) as Service,
MAX(CASE WHEN type = 'Uninstall' THEN count_type END) as Uninstall
FROM (select count(type) as count_type , type
from tasks
group by type) T
This is done with conditional aggregation: 这是通过条件聚合完成的:
select
sum(type = 'Trial') as trial,
sum(type = 'New') as new,
sum(type = 'Service') as service,
sum(type = 'Uninstall') as uninstall
from mytable;
true is 1 and false is 0 in MySQL, so we can use SUM
, to count matches. 在MySQL中,true为1,false为0,因此我们可以使用
SUM
来计算匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.