[英]Row number over partition by usage
I would like to filter the below table based on the week column, but only when the year week combination is a max.我想根据周列过滤下表,但仅当年周组合为最大值时。
In the below example I want my output to only select rows with year 2022 and week 1 as that is the latest year week combination.在下面的示例中,我希望我的 output 仅包含 2022 年和第 1 周的 select 行,因为这是最新的年周组合。
I am thinking to use a row number over partition by but did not have any success.我正在考虑在分区依据上使用行号,但没有成功。
Car colour year week
aaa red 2021 52
aaa black 2021 51
bbb red 2022 1
bbb yellow 2022 1
From Oracle 12, you can use:来自 Oracle 12,您可以使用:
SELECT *
FROM table_name
ORDER BY year DESC, week DESC
FETCH FIRST ROW WITH TIES;
Or, in earlier version, you can use:或者,在早期版本中,您可以使用:
SELECT car, colour, year, week
FROM (
SELECT t.*,
RANK() OVER (ORDER BY year DESC, week DESC) AS rnk
FROM table_name t
)
WHERE rnk = 1;
Which, for the sample data:其中,对于示例数据:
CREATE TABLE table_name (Car, colour, year, week) AS
SELECT 'aaa', 'red', 2021, 52 FROM DUAL UNION ALL
SELECT 'aaa', 'black', 2021, 51 FROM DUAL UNION ALL
SELECT 'bbb', 'red', 2022, 1 FROM DUAL UNION ALL
SELECT 'bbb', 'yellow', 2022, 1 FROM DUAL;
Both output:两者都是 output:
CAR车 COLOUR颜色 YEAR年 WEEK星期 bbb bbb red红色的 2022 2022年 1 1个 bbb bbb yellow黄色 2022 2022年 1 1个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.