[英]Count different rows from one table
I have table t1
: 我有表t1
:
id|id_title|action
The data in table: 表中的数据:
1|1|like
2|1|like
3|1|unlike
4|2|share
5|2|share
So I want to get next result from query: 所以我想从查询中获得下一个结果:
id|count like|count unlike|count share
1|2|1|0
2|0|0|2
I try to use next query: 我尝试使用下一个查询:
SELECT id_title, ( Select Count(id) From T1 WHERE action='like') As CountOfItems FROM T1 GROUP BY id_title
But it return count of first row always. 但它总是返回第一行的数量。 What I must do? 我应该做什么? Or maybe I must changed structure of table? 或许我必须改变表的结构?
Just use conditional aggregation. 只需使用条件聚合。
select
id_title
,sum(case when action='like' then 1 else 0 end) As Count_Like
,sum(case when action='unlike' then 1 else 0 end) As Count_Unlike
,sum(case when action='share' then 1 else 0 end) As Count_Share
FROM T1
GROUP BY id_title
SELECT id_title AS id, SUM(action='like') AS 'count like',
SUM(action='unlike') AS 'count unlike', SUM(action='share')
AS 'count share' FROM t1 GROUP BY id_title
Let me know if that worked for you. 如果这对您有用,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.