我有一个包含以下字段的表:
id,奖杯,注册
每一行都是投票,例如:
32, 1, hk57 hxz
33, 1, hk57 hxz
34, 1, sj2 ghd
35, 2, hk57 hxz
36, 2 sj2 ghd
这将是汽车hk57 hxz赢得奖杯1和1投票赢得奖杯1的2票。两辆车各有一票奖杯2
如何编写查询以总计每辆车每个奖杯的投票数?
或者用另一种方式计算同一个奖杯对同一个奖杯的次数并用奖杯显示?
答案 0 :(得分:0)
我现在没办法尝试这个,但我确定你只需要group by
奖杯和count
注册,例如:
SELECT trophy, registration, count(*) FROM your_table
GROUP BY registration, trophy
count(*)
表示计算寄存器group by
表示'并按此列对其进行分组' 这里有一些参考资料:
https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html
除了其他答案之外,如果您需要,我建议给您的计数别名(*)!
SELECT registration, trophy, count(*) as votes FROM your_table
GROUP BY registration, trophy
所以count(*)列将被称为更漂亮的投票
答案 1 :(得分:0)
SELECT registration, COUNT(trophy) FROM table_name GROUP BY registration, trophy;
答案 2 :(得分:0)
由于您需要为每个注册和奖杯配对单独计数,请使用GROUP BY
中的两列。
SELECT registration, trophy, COUNT(*) AS votes
FROM yourTable
GROUP BY registration, trophy
ORDER BY trophy, registration
答案 3 :(得分:0)
你需要通过奖杯和注册进行分组。
SELECT count(*) as TotalVotes, trophy, registration FROM your_table
GROUP BY trophy, registration
结果如下:
TotalVotes | trophy | registration
2 | 1 | hk57 hxz
1 | 1 | sj2 ghd
1 | 2 | sj2 ghd
1 | 2 | hk57 hxz