0

我有一张看起来像这样的桌子

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

我该如何解决这个问题?

4

3 回答 3

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)
于 2012-08-29T05:40:13.037 回答
3

你可以试试

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

SQLFiddle 演示

于 2012-08-29T05:46:14.543 回答
1
SELECT id,rating,count(rating) from table group by id,rating
于 2012-08-29T05:37:56.250 回答