Reputation: 467
Per each product_id
based on the column year
, I would like to get the value from column name
that would represent the earliest name
.
year | name | product_id | initial_name |
---|---|---|---|
2016 | Pepsi. | 123456 | Pepsi. |
2017 | Pepsi co. | 123456 | Pepsi. |
2017 | Cola | 567890 | Cola |
2018 | Coca-Cola | 567890 | Cola |
2019 | Coca-Colas | 567890 | Cola |
I started implementing the logic in this way but there must be an easier way:
SELECT *,
CASE WHEN year = date_min THEN name END name_min
FROM (
SELECT *,
MIN(year) OVER (PARTITION BY product_id) year_min
FROM table
Upvotes: 0
Views: 317
Reputation: 164214
Use FIRST_VALUE()
window function:
SELECT *,
FIRST_VALUE(name) OVER (PARTITION BY product_id ORDER BY year) name_min
FROM tablename;
Upvotes: 2