MySQL table is like this (VoteID is PK):
VoteID VoteValue CommentID
1 -1开发者_JAVA技巧 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?
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
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
精彩评论