2012-02-21 33 views
2

這是我的數據庫中的「評級」表。COUNT從單欄並將其分成2列

attraction  customer  rate 
------------------------------------ 
attrac1   cust1   like 
attrac2   cust1   dislike 
attrac1   cust2   like 

要我寫什麼SQL,使輸出變成這個樣子

attraction  like  dislike 
---------------------------------- 
attrac1   2   0 
attrac2   0   1 

我想這

SELECT a_id, 
(SELECT COUNT(rate) FROM rating WHERE rate = 'like') as 'Like', 
(SELECT COUNT(rate) FROM rating WHERE rate = 'dislike') as 'Dislike' 
FROM rating 

但我不能得到我想要的結果。

回答

1

這是一個方法:

SELECT a_id, 
    SUM(Case when rate='like' then 1 else 0 end) as 'Like', 
    SUM(Case when rate='dislike' then 1 else 0 end) as 'Dislike' 
FROM rating 
Group BY A_id 
+0

感謝您的快速回復。我從來不知道SQL中可以有一個if else語句。 – Joseph 2012-02-21 09:57:40

2
SELECT Attraction, 
     COUNT(CASE WHEN Rate = 'Like' THEN Customer END) [Like], 
     COUNT(CASE WHEN Rate = 'DisLike' THEN Customer END) [DisLike] 
FROM Rating 
GROUP BY Attraction