Select 最后一行使用 ROW_NUMBER 函数

Select last row using ROW_NUMBER function

我只是想知道是否有任何方法可以 select 基于 ROW_NUMBER() 函数的最后一行?基本上我想 select 每个 department_id 最后一个(最多一个)emp_id.

SELECT 
    department_id, last_name, employee_id, 
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_id) AS emp_id
FROM 
    employees;

输出:

DEPARTMENT_ID LAST_NAME                 EMPLOYEE_ID     EMP_ID
------------- ------------------------- ----------- ----------
           10 Whalen                            200          1
           20 Hartstein                         201          1
           20 Fay                               202          2
           30 Raphaely                          114          1
           30 Khoo                              115          2
           30 Baida                             116          3
           30 Tobias                            117          4
           30 Himuro                            118          5
           30 Colmenares                        119          6
           40 Mavris                            203          1
. . .
          100 Popp                              113          6
          110 Higgins                           205          1
          110 Gietz                             206          2

是的,您可以添加降序,然后使用该列进行过滤:

SELECT *
FROM (
  SELECT department_id, last_name, employee_id,
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_id) AS emp_id,
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_id DESC) l_emp_id 
   FROM employees
) 
WHERE l_emp_id = 1

在每个分区和过滤器中 ORDER BY employee_id DESC 之后使用您的查询来获取每个组的第一行:

SELECT t.department_id, t.last_name, t.employee_id
FROM (  
  SELECT department_id, last_name, employee_id, 
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_id DESC) rn 
  FROM employees
) t
WHERE t.rn = 1

参见demo
结果:

> DEPARTMENT_ID | LAST_NAME  | EMPLOYEE_ID
> ------------: | :--------- | ----------:
>            10 | Whalen     |         200
>            20 | Fay        |         202
>            30 | Colmenares |         119
>            40 | Mavris     |         203
>           100 | Popp       |         113
>           110 | Gietz      |         206