对GROUP BY agregats进行排序

时间:2011-11-15 10:34:21

标签: mysql group-by

想象一下这张表t1

+----------+-------+--------+
| group_id |  name |  age   |
+----------+-------+--------+
|    1     |   A1  |   1    |
|    1     |   A2  |   2    |
|    1     |   A3  |   3    |
|    2     |   B1  |   4    |
+----------+-------+--------+

在MySQL中使用以下查询,

SELECT group_id, name, COUNT(*) FROM t1 GROUP BY group_id

我们得到了,

+----------+-------+--------+----------+
| group_id |  name |  age   | COUNT(*) |
+----------+-------+--------+----------+
|    1     |   A1  |   2    |    3     |
|    2     |   B1  |   4    |    1     |
+----------+-------+--------+----------+

正如您在此处所见,值name = A1和age = 2可能不是来自同一记录。


我的问题是,如何控制显示nameage列的单个结果,因此内容来自一条记录?有没有办法以某种方式对它们进行排序?例如按年龄顺序按相反顺序排序

+----------+-------+--------+----------+
| group_id |  name |  age   | COUNT(*) |
+----------+-------+--------+----------+
|    1     |   A3  |   3    |    3     |
|    2     |   B1  |   4    |    1     |
+----------+-------+--------+----------+

感谢。

3 个答案:

答案 0 :(得分:1)

我不知道你为什么说你的查询有效。您还应按名称分组......

SELECT group_id, name, COUNT(*) FROM t1 GROUP BY group_id, name

如果您只想获得其中一个,请尝试:

SELECT group_id, MIN(name), COUNT(*) FROM t1 GROUP BY group_id

答案 1 :(得分:0)

SELECT group_id, name, COUNT(*)
FROM t1 
WHERE name IN ( 'xxx', 'yyy', ..., 'zzz' )
GROUP BY group_id
SORT BY COUNT(*)

答案 2 :(得分:0)

我不知道完全控制,但你可以这样做

SELECT student_name, MIN(test_score), MAX(test_score)
        FROM student
        GROUP BY student_name;