Bro
Bro

Reputation: 57

Select last row using ROW_NUMBER function

I am just wondering if there is any way to select the last row based on ROW_NUMBER() function? Basically I would like to select for each department_id THE LAST (max one) 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;

Output:

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

Upvotes: 1

Views: 2100

Answers (2)

forpas
forpas

Reputation: 164089

Use your query after you ORDER BY employee_id DESC inside each partition and filter to get the 1st row of each group:

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

See the demo.
Results:

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

Upvotes: 1

Lukasz Szozda
Lukasz Szozda

Reputation: 175696

Yes, you could add descending order and then filter using that column:

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

Upvotes: 2

Related Questions