假设我有一个名为votes
的表,该表中的一个名为vote_type
的列可以是0或1.如何获取COUNT
vote_type
} vote_type
是1
?
现在,我可以通过此查询选择整体vote_type
的计数,但不能计算vote_type
的计数,其中它是1或0:
SELECT COUNT(votes.vote_id) AS vote_count
FROM votes
WHERE <some condition>
ORDER BY vote_count
如何选择vote_types的总数,vote_types的数量= 1,vote_types的数量= 0,以及total_value的总数(votetypes = 1减去votetypes = 0),并按总票数排序?
编辑:注意1&amp; 0不是投票的内在值,而是正投票和反投票的布尔表达式。
答案 0 :(得分:2)
我不知道你到底想要做什么,但如果你想用Vote_Type = 1计算所有选票 尝试
SELECT COUNT(votes.vote_id) AS vote_count
FROM votes
WHERE votes.vote_type=1
或者如果你需要总结选票</ p>
SELECT SUM(votes.vote_type) AS vote_sum
FROM votes
WHERE votes.vote_type=1
答案 1 :(得分:1)
SELECT COUNT(*) TotalVotes,
SUM(CASE WHEN vote_type = 1 THEN 1 ELSE 0 END) TotalVoteOne,
SUM(CASE WHEN vote_type = 0 THEN 1 ELSE 0 END) TotalVoteZero,
SUM(CASE WHEN vote_type = 1 THEN 1 ELSE 0 END) -
SUM(CASE WHEN vote_type = 0 THEN 1 ELSE 0 END) TotalVoteValue
FROM votes
-- WHERE ....
-- ORDER ....
当你说按总票数命令时 - 它实际上没有意义,因为结果中的总行数只有一个。
您也可以将其包装在子查询中,
SELECT TotalVotes,
TotalVoteOne,
TotalVoteZero,
(TotalVoteOne - TotalVoteZero) AS TotalVoteValue
FROM
(
SELECT COUNT(*) TotalVotes,
SUM(CASE WHEN vote_type = 1 THEN 1 ELSE 0 END) TotalVoteOne,
SUM(CASE WHEN vote_type = 0 THEN 1 ELSE 0 END) TotalVoteZero
FROM tableName
-- WHERE ....
-- ORDER BY TotalVoteValue DESC
) a
答案 2 :(得分:1)
尝试从这样的事情开始:
SELECT SUM(CASE WHEN votetype = 1 then 1 else 0 end) AS vote_count_1,
SUM(CASE WHEN votetype = 0 then 1 else 0 end) AS vote_count_0
FROM votes
WHERE <some condition>
ORDER BY vote_count
答案 3 :(得分:1)
修改:添加了net_vote
列,我认为这是你所追求的“vote1 minus vote0
”。
Select
Sum(Case v.vote_type When 1 then 1 else -1 end) as net_vote
From
Votes v
Where
<some condition>
我删除了order by
,因为这只会返回一行。
答案 4 :(得分:0)
$query = "SELECT *FROM votes WHERE vote_type=1 || vote_type=0";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$WhereVoteIsOne=$row['vote_type'];
foreach ($WhereVoteIsOne as $votesCount) { echo $votesCount."<br/>";}