簡體   English   中英

MySQL數量和總數

[英]MySQL count and total

我的桌子上有很多票,每張選票都反對一個帖子。 我想做的是計算每次投票的總數。

表看起來像這樣:

    vote
    -----
    1
    2
    3
    1
    2
    3
    4
    5
    2
    2
    2
    2
    ...and so on...

我如何計數記錄,例如在該列表中1x2、2x6、3x2、4x1和5x1次。

select vote, count(votes) as vt
from t_your_table
group by vote

要獲得所需的內容,可以使用GROUP BY和COUNT:

SELECT vote, COUNT(*) AS cnt
FROM votes
GROUP BY vote

結果:

vote  cnt
1     2  
2     6  
3     2  
4     1  
5     1

計數為零的投票將不會在此結果集中顯示。 如果要包含零計數,則需要使用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

結果:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM