2016-05-10 37 views
2

我有表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 

但它總是返回第一行的計數。我應該做什麼?或者,也許我必須改變桌子的結構?

+0

我不明白你想要對錶格應用什麼查詢,你能詳細解釋一下嗎? – Webeng

+0

我編輯了我的答案,它現在應該工作 – Webeng

回答

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 

讓我知道這是否爲你工作。

+0

失蹤FROM子句 – Thamilan

+0

@Thamizhan謝謝:) – Webeng

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 
+0

或者,因爲它的MySQL,只是'SUM(action ='like')' – Strawberry