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表达式中获得所需?
答案 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