[英]Get the lowest value per column based on another column
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
.每个
product_id
基于列year
,我想从表示最早name
的列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
Use FIRST_VALUE()
window function:使用
FIRST_VALUE()
window function:
SELECT *,
FIRST_VALUE(name) OVER (PARTITION BY product_id ORDER BY year) name_min
FROM tablename;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.