views:

37

answers:

2

Hi, all!

MySQL table is like this (VoteID is 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

I need a result:

CommentID    Plus    Minus
    1          1      3 
    2          2      1 

Sum of "Pluses", Sum of "Minuses" groupped by CommentID Is it possible to get desired in one SQL expression?

+3  A: 
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
Adam Bernier
Of course "CASE" :) Thank you :)
x17az
A: 

You need a query in the lines of:

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
Anax
Thank you very much :)
x17az