计算upvotes和downvotes

时间:2012-12-31 14:03:43

标签: mysql

我有一个这样的SQL表:

id  cid     u_id  vote  user_ip     date_added 
--------------------------------------------------------------
67  188     13      0   127.0.0.1   1356686070
68  188     15      1   127.0.0.1   1356686765
69  291     13      1   127.0.0.1   1356688859
70  62      15      1   127.0.0.1   1356695284
71  370     23      1   127.0.0.1   1356892215
73  232     23      1   127.0.0.1   1356893261
74  152     23      1   127.0.0.1   1356893591
76  75      15      1   127.0.0.1   1356924002
77  201     15      1   127.0.0.1   1356927284

vote列中,0代表downvote,而1代表upvote。我将如何计算每个cid的downvotes和upvotes?

结果将是这样的:

cid   upvotes  downvotes
188   1        1
291   1        0
291   1        0

1 个答案:

答案 0 :(得分:4)

SELECT cid,
  SUM(vote) AS upvoted,
  SUM(CASE
        WHEN vote = 0
        THEN 1
        ELSE 0
      END) AS downvoted
FROM yourtablename
GROUP BY cid;