我想根据以下条件对列值求和

 USERID | QUERYID | UPVOTE | DOWNVOTE
   1    | 15      | 1      |  0
   0    | 15      | 0      | -1
   6    | 15      | 0      | -1
   1    | 7       | 1      |  0
   8    | 7       | 1      |  0

我有兴趣获得此要求的结果,例如
for QUERYID = 15它应该返回我-1为(SUM(UPVOTE)+ SUM(DOWNVOTE))
对于QUERYID = 7,应该使用与上述相同的逻辑给我2。
我已经尝试过以下方式
select (SUM(UPVOTE)+ SUM(DOWNVOTE)) as "TOTAL" from "MY_TABLE" where "QUERYID" in (15, 7)';但是给我所有列的总和与两个queryId的组合结果。

最佳答案

您需要一个group by子句,以针对queryid的唯一值生成单独的结果:

SELECT   (SUM(upvote) + SUM(downvote)) AS "TOTAL"
FROM     mytable
-- Possibly also add a where clause here if you only want to do this for some queryids
GROUP BY queryid

08-03 22:34