在sql 查询过程中经常有一种查询,某一类别的第一名 比如:
limingyao=# \d employee
Table "public.employee"
Column | Type | Collation | Nullable | Default
------------+---------+-----------+----------+---------
id | integer | | |
name | text | | |
department | text | | |
salary | integer | | |
查询 employee表每一个部门工资最高的员工信息
- 第一种最直观的写法
SELECT
*
FROM
employee
WHERE
(department, salary) IN (
SELECT
department,
MAX(salary)
FROM
employee
GROUP BY
department
)
ORDER BY
department;
- 使用窗口函数 row_number()
WITH ranked_employees AS (
SELECT
ROW_NUMBER() OVER (
PARTITION BY department ORDER BY salary DESC
) AS rn,
*
FROM
employee
)
SELECT
*
FROM
ranked_employees
WHERE
rn = 1
ORDER BY
department;
- 使用 distinct on
SELECT DISTINCT ON (department)
*
FROM
employee
ORDER BY
department,
salary DESC;
Note: 这三种写法结果是不相同?
https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group