2012-02-21 32 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