计算一个表

时间:2016-05-10 12:56:58

标签: mysql sql

我有表t1

id|id_title|action

表格中的数据:

1|1|like
2|1|like
3|1|unlike
4|2|share
5|2|share

所以我想从查询中获得下一个结果:

id|count like|count unlike|count share

1|2|1|0
2|0|0|2

我尝试使用下一个查询:

SELECT id_title, ( Select Count(id) From T1 WHERE action='like') As CountOfItems FROM T1 GROUP BY id_title

但它始终返回第一行的计数。我应该做什么?或许我必须改变表的结构?

2 个答案:

答案 0 :(得分:6)

只需使用条件聚合。

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

答案 1 :(得分:2)

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

如果这对您有用,请告诉我。