MySQL GROUP BY数量

时间:2010-07-09 14:25:53

标签: sql mysql group-by aggregate-functions

MySQL表是这样的(VoteID是PK):

VoteID  VoteValue CommentID
1         -1         1
2         -1         1
3          1         1
4         -1         1
5          1         2
6          1         2
7         -1         2

我需要一个结果:

CommentID    Plus    Minus
    1          1      3 
    2          2      1 

“加号”的总和,由CommentID组成的“减号”的总和 是否可以在一个SQL表达式中获得所需?

2 个答案:

答案 0 :(得分:4)

SELECT 
    CommentID,
    SUM(CASE WHEN VoteValue > 0 THEN 1 ELSE 0 END) AS PLUS,
    SUM(CASE WHEN VoteValue < 0 THEN 1 ELSE 0 END) AS MINUS

FROM 
    mytable

GROUP BY 
    CommentID

答案 1 :(得分:0)

您需要查询以下行:

SELECT CommentID,
    SUM(IF(VoteValue > 0, 1, 0)) AS Plus,
    SUM(IF(VoteValue < 0, 1, 0)) AS Minus
FROM yourTable
GROUP BY CommentID
ORDER BY CommentID