[英]MySQL count and total
I have a table with a number of votes recorded in it, each vote goes against a post. 我的桌子上有很多票,每张选票都反对一个帖子。 What I want to be able to do is count the total occurances of each vote.
我想做的是计算每次投票的总数。
Table looks like this: 表看起来像这样:
vote
-----
1
2
3
1
2
3
4
5
2
2
2
2
...and so on...
How can I count the records, eg In that list 1x2, 2x6, 3x2, 4x1 and 5x1 times. 我如何计数记录,例如在该列表中1x2、2x6、3x2、4x1和5x1次。
select vote, count(votes) as vt
from t_your_table
group by vote
To get what you want you can use GROUP BY and COUNT: 要获得所需的内容,可以使用GROUP BY和COUNT:
SELECT vote, COUNT(*) AS cnt
FROM votes
GROUP BY vote
Result: 结果:
vote cnt 1 2 2 6 3 2 4 1 5 1
Votes that have zero count will not be represented in this result set. 计数为零的投票将不会在此结果集中显示。 If you want to have these included with a count of zero then you will need to use an OUTER JOIN with a table listing all the possible votes.
如果要包含零计数,则需要使用OUTER JOIN及其表格列出所有可能的投票。
SELECT
possible_votes.vote,
COUNT(votes.vote) AS cnt
FROM possible_votes
LEFT JOIN votes ON possible_votes.vote = votes.vote
GROUP BY possible_votes.vote
Result: 结果:
vote cnt 1 2 2 6 3 2 4 1 5 1 6 0
查看MySQL手册以了解GROUP BY和COUNT的组合。
SELECT vote, COUNT(*) as total
FROM votes
GROUP BY vote
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.