2012-12-31 59 views
-8

我有一個SQL表是這樣的:計數upvotes和downvotes

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表示給予好評。如何計算每個cid的降薪和點贊數?

其結果將是這樣的:

cid upvotes downvotes 
188 1  1 
291 1  0 
291 1  0 
+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;