0

这是我的桌子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 9votes表中,结果应该是1 (2-1+0=1). 这里显示为0

你能看出我哪里出错了,我怎么能把它弄好?

4

1 回答 1

3

我认为您不想以否定的方式显示投票。所以。首先计算投票数而不是减去不同的数量......试试这样......

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

Sql 小提琴演示

于 2013-05-10T04:54:12.120 回答