[英]SQL group by get value on one column based on order of another column
Suppose I have the following table in SQL:假设我在 SQL 中有下表:
id ![]() |
year![]() |
value![]() |
---|---|---|
1 ![]() |
2022 ![]() |
10 ![]() |
1 ![]() |
2020 ![]() |
5 ![]() |
2 ![]() |
2019 ![]() |
10 ![]() |
2 ![]() |
2021 ![]() |
4 ![]() |
3 ![]() |
2018 ![]() |
2 ![]() |
3 ![]() |
2017 ![]() |
10 ![]() |
And for each id, I want the last value based on the year.对于每个 id,我想要基于年份的最后一个值。 The final table would be:
决赛桌将是:
id ![]() |
year![]() |
value![]() |
---|---|---|
1 ![]() |
2022 ![]() |
10 ![]() |
2 ![]() |
2021 ![]() |
4 ![]() |
3 ![]() |
2018 ![]() |
2 ![]() |
I know I have to use some sort of group by in id than order by year and get the first value, but I don't know what aggregate function that would be.我知道我必须在 id 中使用某种分组而不是按年份排序并获得第一个值,但我不知道 function 的总和是多少。
My attempt was to group by id while ordering by year and then getting the first value:我的尝试是按 id 分组,同时按年份排序,然后获得第一个值:
SELECT id, MAX(year), FIRST(value)
FROM t
GROUP BY id
ORDER BY year desc
But this doesn't work.但这不起作用。
Yet another option is using the FETCH FIRST n ROWS WITH TIES
clause, which allows to get the first rows with respect an ordering.另一个选项是使用
FETCH FIRST n ROWS WITH TIES
子句,它允许获取关于排序的第一行。 Applying the ordering using the ROW_NUMBER
window function, will make you extract all rows with ranking = 1, tied.使用
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;
This is simple task for window functions:这是 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;
You can use a window function:您可以使用 window function:
(partition by id order by year desc)
The first answer already gives the structure of the SQL making use of row_number()
to filter the result.第一个答案已经给出了使用
row_number()
过滤结果的 SQL 的结构。 Here is an alternative:这是一个替代方案:
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.