我有一个表“vote_benefits”,其中包含以下架构: id(int 11) id_benefit(int 11) 评级(int 11) 手机(varchar 10) inputdate(日期)
人们可以为每件物品投票(通过星级评分系统),从1到5星。我必须为每项福利获得每个评级的投票数。
内容类似于
id id_b rating cellphone inputdate
1 2 5 123456789 2011-01-04 18:56:38
2 2 4 123456789 2011-01-04 19:03:27
3 2 4 123456789 2011-01-05 10:24:29
4 2 4 123456789 2011-01-05 10:24:33
5 2 5 123456789 2011-01-05 10:24:37
6 2 5 123456789 2011-01-05 10:24:42
7 2 4 123456789 2011-01-05 10:24:43
8 2 5 123456789 2011-01-05 10:24:44
9 2 4 123456789 2011-01-05 10:24:45
10 2 5 123456789 2011-01-05 10:24:48
11 2 5 123456789 2011-01-05 10:25:42
12 3 4 123456789 2011-01-05 10:49:20
13 3 5 123456789 2011-01-05 10:49:21
14 3 4 123456789 2011-01-05 10:49:22
15 3 5 123456789 2011-01-05 10:52:44
16 3 5 123456789 2011-01-05 10:52:45
17 3 4 123456789 2011-01-05 10:53:04
18 3 4 123456789 2011-01-05 10:53:05
我希望从这些按照id_benefit分组的最多投票权益中获益。 我到目前为止
SELECT id_benefit, count( * ) AS votes, rating
FROM `vote_benefits
GROUP BY id_benefit, rating
给了我
id_b votes rating
2 5 4
2 6 5
3 4 4
3 3 5
但是我想通过id_b对这些进行分组,获得每个id_b投票最多的行:
id_b votes rating
2 6 5
3 4 4
我读过像SQL - select distinct records in one field with highest records from another field这样的链接,但我不明白如何根据我的需要调整它。
答案 0 :(得分:1)
我相信以下内容应该有效:
SELECT id_b, MAX(votes), rating
FROM (SELECT id_benefit, count( * ) AS votes, rating
FROM `vote_benefits
GROUP BY id_benefit, rating)
GROUP BY id_b
答案 1 :(得分:1)
select
id_b, max(rating_count), rating
from
(
select id_b, rating, count(*) as rating_count
from vote_benefits
group by id_b, rating
) as tbl
group by id_b;