如果第一列相等,Mysql Group按第二列?

时间:2012-08-29 05:34:05

标签: mysql group-by

我有一张看起来像这样的表

id | rating
1  | 1
1  | 3
1  | 1
1  | 2
2  | 3
2  | 3
2  | 1
等等,你明白了。

无论如何,我想最终得到这个结果集

id | rating | num
1  | 1      | 2
1  | 3      | 1
1  | 2      | 1
2  | 3      | 2
2  | 1      | 1

所以,我想要做的是将评级分为,只要ID是相同的

我以为我可以做group by id, rating而只是假设它只会在两列相同的情况下进行分组,但如果任何一列都相同,它就不会分组,所以我最终会用

id | rating | num
1  | 1      | 7

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

我不明白你遇到的问题。此查询适用于我:

select 
  id, rating, COUNT(rating) as num 
FROM rating 
GROUP BY id, rating 
ORDER BY id, rating ASC;

而且,为了彻底,这是我的整个测试会议:

mysql> create table rating (id int, rating int);
Query OK, 0 rows affected (0.04 sec)

mysql> insert into rating values (1,1),(1,3),(1,1),(1,2),(2,3),(2,3),(2,1);
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0

mysql> select id, rating, COUNT(rating) as num FROM rating GROUP BY id, rating;
+------+--------+-----+
| id   | rating | num |
+------+--------+-----+
|    1 |      1 |   2 | 
|    1 |      2 |   1 | 
|    1 |      3 |   1 | 
|    2 |      1 |   1 | 
|    2 |      3 |   2 | 
+------+--------+-----+
5 rows in set (0.00 sec)

答案 1 :(得分:3)

你可以尝试

SELECT id,rating,COUNT(rating) AS num 
FROM table1 
GROUP BY id,rating
ORDER BY id ASC

SQLFiddle Demo

答案 2 :(得分:1)

SELECT id,rating,count(rating) from table group by id,rating