在sql 查詢過程中經(jīng)常有一種查詢,某一類別的第一名 比如:
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;
- 使用窗口函數(shù) 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: 這三種寫法結(jié)果是不相同?
https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group