在这种情况下如何避免-1

时间:2013-05-10 04:38:12

标签: mysql sql

这是我的表votes,其中voteType 1 = a negative vote, voteType 0 = a positive vote

"id"    "votedElm"  "voteType"  "voteProcessed" "country"
"3"     "6"         "1"         "0"             "US"//1-1=0

"4"     "8"         "0"         "0"             "US"//2+0-1=1
"9"     "8"         "1"         "0"             "US"

"5"     "9"         "0"         "0"             "US"//2+0-1=1
"10"    "9"         "1"         "0"             "US"

这是我的表likes

"id"    "type"  "parent"    "country"   "votes"
    6       10      3           US          1
    8       10      7           US          2
    9       10      7           US          2

在上面,我运行以下sql来计算votes中的投票数,然后从喜欢中添加或减去它们。

SELECT
  votedElm,
  SUM(CASE WHEN voteType = 0 THEN 1 ELSE -1 END) AS Totalcount 
FROM votes 
WHERE country = 'US'
GROUP BY votedElm;

但是,对于id 6 in votes,使用上述查询时,结果为-1。所以,1 (in likes) minus -1 = 2。我想要的结果是0。 另外,对于8 and 9表格中的votes,结果应为1 (2-1+0=1)。它显示为0

你能看到我出错的地方以及如何做到这一点吗?

1 个答案:

答案 0 :(得分:3)

我认为你不想在负面显示投票。所以首先计算投票数量减去不同数量的投票......试试这样......

 Select voteby,(Count(votetype)-Sum(Case when votetype=1 then 1 else 0 end)) as b
    from t group by voteby

Sql Fiddle Demo