V
V
Vladeo DdossS2020-08-31 11:56:59
SQL
Vladeo DdossS, 2020-08-31 11:56:59

How to select latest entry by name and date?

There is a table
id | name | salary | period start | period end
1 | Egor | 344 | 2020-08-01 | 2020-08-31
2 | Arthur | “567” | 2020-08-01 | 2020-08-31
3 | Egor | 768 | 2020-08-01 | 2020-08-31
4 | Arthur | “356” | 2020-08-01 | 2020-08-31
5 | Dima | 864 | 2020-08-01 | 2020-08-31
6 | Dima | 357 | 2020-08-01 | 2020-08-31
7 | Dima | 865 | 2020-08-01 | 2020-08-31

Expected Result :
Get latest records by “id” for each name Egor, Artur, Dima and date from 2020-08-01 to 2020-08-31

3 | Egor | 768 | 2020-08-01 | 2020-08-31
4 | Arthur | “356” | 2020-08-01 | 2020-08-31
7 | Dima | 865 | 2020-08-01 | 2020-08-31

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-08-31
@Vladeo

You can find the maximum identifiers for each name in a subquery, and then simply select the data by them:

SELECT *
FROM salary 
WHERE id IN (SELECT MAX(id) FROM salary GROUP BY name);

M
Maxim Y, 2020-09-01
@x_shader

SELECT *
FROM
  (SELECT id,
          name,
          salary,
          period-start,
          period-end,
          row_number() OVER (PARTITION BY name ORDER BY id DESC) AS rn
   FROM your_table
   WHERE period-start = ...
     AND period-end = ...)
WHERE rn = 1

Only instead of * you need to list the required fields in the actual request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question