PostgreSQL DISTINCT ON
用法:
postgres=# select distinct on(course)id,name,course,score from student;
id | name | course | score ----+--------+--------+-------
10 | 周星驰 | 化学 | 83
8 | 周星驰 | 外语 | 88
2 | 周润发 | 数学 | 99
14 | 黎明 | 物理 | 90
6 | 周星驰 | 语文 | 91
(5 rows)
2. 获取每门课程的最高分 postgres=# select distinct on(course)id,score from student order by course,score desc;
id | name | course | score ----+--------+--------+-------
5 | 周润发 | 化学 | 87
13 | 黎明 | 外语 | 95
2 | 周润发 | 数学 | 99
14 | 黎明 | 物理 | 90
6 | 周星驰 | 语文 | 91
(5 rows)
3. 如果指定ORDER BY 必须把分组的字段放在最左边 postgres=# select distinct on(course)id,score from student order by score desc;
ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: select distinct on(course)id,score from student ...
postgres=# select distinct on(course)id,score from student order by score desc,course;
ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: select distinct on(course)id,score from student ...
4. 获取每门课程的最高分同样可以使用IN子句来实现 postgres=# select * from student where(course,score) in(select course,max(score) from student group by course);
id | name | course | score
----+--------+--------+-------
2 | 周润发 | 数学 | 99
5 | 周润发 | 化学 | 87
6 | 周星驰 | 语文 | 91
13 | 黎明 | 外语 | 95
14 | 黎明 | 物理 | 90
(5 rows)
5. 在 row_number() over(),distinct on和in子句之间有一个小区别
postgres=# update student set score =99 where name='黎明' and course='数学';
UPDATE 1 postgres=# select * from student where course ='数学';
id | name | course | score
----+--------+--------+-------
31 | 周润发 | 数学 | 99
36 | 周星驰 | 数学 | 81
41 | 黎明 | 数学 | 99
(3 rows)
postgres=# select id,score from (select *,row_number() over(partition by course order by score desc)rn from student)t where t.rn=1 order by course;
id | name | course | score
----+--------+--------+-------
34 | 周润发 | 化学 | 87
42 | 黎明 | 外语 | 95
41 | 黎明 | 数学 | 99
43 | 黎明 | 物理 | 90
35 | 周星驰 | 语文 | 91
(5 rows)
postgres=# select distinct on(course) * from student order by course,score desc,course;
id | name | course | score ----+--------+--------+-------
34 | 周润发 | 化学 | 87
42 | 黎明 | 外语 | 95
41 | 黎明 | 数学 | 99
43 | 黎明 | 物理 | 90
35 | 周星驰 | 语文 | 91
(5 rows)
postgres=# select * from student where(course,score) in (select course,max(score) from student group by course) order by course;
id | name | course | score
----+--------+--------+-------
34 | 周润发 | 化学 | 87
42 | 黎明 | 外语 | 95
31 | 周润发 | 数学 | 99
41 | 黎明 | 数学 | 99
43 | 黎明 | 物理 | 90
35 | 周星驰 | 语文 | 91
(6 rows)
因为row_number() over()是根据行号来取的,distinct on是返回排序之后的第一行,所以它们只是返回一个最高分。 postgres=# select id,score from(select *,rank() over(partition by course order by score desc)sn from student)t where sn=1;
id | name | course | score
----+--------+--------+-------
5 | 周润发 | 化学 | 87
13 | 黎明 | 外语 | 95
12 | 黎明 | 数学 | 99
2 | 周润发 | 数学 | 99
14 | 黎明 | 物理 | 90
6 | 周星驰 | 语文 | 91
(6 rows)
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |