繁体   English   中英

SQL 分组,根据另一列的顺序在一列上获取值

[英]SQL group by get value on one column based on order of another column

假设我在 SQL 中有下表:

ID 价值
1 2022 10
1 2020 5
2 2019 10
2 2021 4
3 2018 2
3 2017 10

对于每个 id,我想要基于年份的最后一个值。 决赛桌将是:

ID 价值
1 2022 10
2 2021 4
3 2018 2

我知道我必须在 id 中使用某种分组而不是按年份排序并获得第一个值,但我不知道 function 的总和是多少。

我的尝试是按 id 分组,同时按年份排序,然后获得第一个值:

SELECT id, MAX(year), FIRST(value)
FROM t
GROUP BY id
ORDER BY year desc

但这不起作用。

另一个选项是使用FETCH FIRST n ROWS WITH TIES子句,它允许获取关于排序的第一行。 使用ROW_NUMBER window function 应用排序,将使您提取所有排名 = 1 的行,并列。

SELECT  * 
FROM tab 
ORDER BY ROW_NUMBER() OVER(PARTITION BY id_ ORDER BY year_ DESC)
FETCH FIRST 1 ROWS WITH TIES;

此处查看演示。

这是 window 函数的简单任务:

with row_numbers as (
  select 
      *,
      row_number() over (partition by value order by year desc) rn
  from t
) select id, year, value from row_numbers where rn = 1;

在线 sql 编辑器

您可以使用 window function:

 (partition by id order by year desc)

第一个答案已经给出了使用row_number()过滤结果的 SQL 的结构。 这是一个替代方案:

select distinct id, 
       first_value(year)  over w as year,
       first_value(value) over w as value
from   t
window w as (partition by id order by year desc)
order by id;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM