我的表格就像votes
"id" "votedElm" "voteType" "voteProcessed" "country"
"1" "4" "0" "0" "US"
"2" "5" "0" "0" "US"
"3" "6" "1" "0" "US"
"4" "8" "0" "0" "US"
"5" "9" "0" "0" "US"
"6" "10" "0" "0" "US"
"7" "10" "0" "0" "US"
"8" "10" "0" "0" "US"
"9" "8" "1" "0" "US"
"10" "9" "1" "0" "US"
"11" "20" "1" "0" "US"
"12" "10" "1" "0" "US"
"13" "10" "1" "0" "US"
"14" "20" "0" "0" "US"
"15" "22" "0" "0" "US"
"16" "20" "0" "0" "US"
"17" "21" "0" "0" "US"
"18" "10" "0" "0" "US"
"19" "10" "0" "0" "US"
"20" "20" "0" "0" "US"
"21" "21" "0" "0" "US"
"22" "22" "0" "0" "US"
"23" "22" "0" "0" "US"
"24" "22" "1" "0" "US"
我使用这个sql来区分它并从中求和:
select votedElm, count(votedElm) from votes where country = 'US' and voteType = 0 group by votedElm;
但是,在该表中,我有voteType 0 and 1
。 0
投票为+
,1
投票为-
。
在同一个sql中,可以添加+
个投票,并从总和中扣除-
个投票吗?而不是对此有2个不同的查询?
我可以这样做吗?
答案 0 :(得分:1)
是,就像这样:
SELECT
votedElm,
SUM(CASE WHEN voteType = 0 THEN 1 ELSE -1 END) AS Totalcount
FROM votes
WHERE country = 'US'
GROUP BY votedElm;
请在此处查看:
答案 1 :(得分:1)
SELECT votedElm, count(votedElm),
SUM(IF(voteType = 0, 1, -1)) AS totalVotes
FROM votes
WHERE country = 'US' and voteType = 0
GROUP BY votedElm;
答案 2 :(得分:0)
尝试
SELECT votedElm,SUM(CASE WHEN voteType = '0' THEN '1' ELSE '-1' END) AS count
FROM `votes`
WHERE country = 'US' and voteType = '0'
GROUP BY votedElm;
或者您可以尝试
$sql1 = "SELECT SUM(votedElm) AS count
FROM `votes`
WHERE country = 'US' and voteType = '0'
GROUP BY votedElm";
$res1 = my_sql_query($sql1);
和
$sql2 = "SELECT SUM(votedElm) AS count
FROM `votes`
WHERE country = 'US' and voteType = '1'
GROUP BY votedElm";
$res2 = my_sql_query($sql2);
然后
$res = $res1[0]['count'] - $res2[0]['count'];
答案 3 :(得分:0)
您可以尝试以下解决方案
SELECT
votedElm,
SUM(CASE WHEN voteType = 0 THEN 1 ELSE -1 END) AS Totalcount
FROM votes
WHERE country = 'US'
GROUP BY votedElm;