postgresql group by first 的三种写法

在sql 查询过程中经常有一种查询,某一类别的第一名 比如:

limingyao=# \d employee
                Table "public.employee"
   Column   |  Type   | Collation | Nullable | Default
------------+---------+-----------+----------+---------
 id         | integer |           |          |
 name       | text    |           |          |
 department | text    |           |          |
 salary     | integer |           |          |

查询 employee表每一个部门工资最高的员工信息

  1. 第一种最直观的写法
SELECT  
    *
FROM
    employee
WHERE
    (department, salary) IN (
        SELECT 
            department,
            MAX(salary)
        FROM
            employee
        GROUP BY
            department
    )
ORDER BY
    department;
  1. 使用窗口函数 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;
  1. 使用 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

    原文作者:lmy_8db4
    原文地址: https://www.jianshu.com/p/239b8a3e9e72
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞