【发布时间】:2021-06-26 19:39:28
【问题描述】:
我正在使用这样一张桌子:
create table example_table (ID Number(8), Year Number(8), Data Varchar(4));
insert into example_table
(ID,Year,Data)
(
select 1,2008,1 from dual union
select 1,2010,2 from dual union
select 2,2014,3 from dual union
select 2,2020,4 from dual union
select 2,2009,5 from dual union
select 3,2003,6 from dual union
select 4,2015,7 from dual union
select 4,2014,8 from dual);
select * from example_table;
| ID | Year | Data |
|---|---|---|
| 1 | 2008 | 1 |
| 1 | 2010 | 2 |
| 2 | 2014 | 3 |
| 2 | 2020 | 4 |
| 2 | 2009 | 5 |
| 3 | 2003 | 6 |
| 4 | 2015 | 7 |
| 4 | 2014 | 8 |
在这种情况下,ID 和 Year 列共同构成特定行的唯一标识符。我只想提取给定 ID 的年份最大化的行,例如
| Id | Year | Data |
|---|---|---|
| 1 | 2010 | 2 |
| 2 | 2020 | 4 |
| 3 | 2003 | 6 |
| 4 | 2015 | 7 |
我知道我可以使用相关的子查询来做到这一点,例如
select distinct
ID, Year, Data
from example_table a
where Year =
(select max(year)
from example_table b
where a.id = b.id);
或者我可以用一个通用的表表达式来做到这一点:
with tmp(ID,Year)
as (
select distinct
ID,
max(year)
over (partition by ID)
from example_table)
select distinct
ID, Year, Data
from example_table
inner join tmp
on example_table.ID = tmp.ID
and example_table.year = tmp.year;
从技术上讲,我也可以通过创建另一个表/视图来做到这一点,但我的数据库没有权限来做到这一点。无论如何,这是我必须在我的脚本中完成的一项常见任务,我想减少我生成的查询数量。 只有一个查询有没有办法做到这一点?
我尝试使用HAVING 语句,例如:
select example_table.ID,
max(example_table.YEAR),
example_table.DATA
from example_table
group by ID, DATA
having example_table.YEAR = max(example_table.YEAR);
但这似乎不起作用,因为HAVING 语句仅对组起作用,而我想操作组内的元素。
有没有办法只用一个查询来做到这一点,如果没有,用两个查询来做这件事的最明确的方法是什么?
【问题讨论】:
-
top n per group逻辑需要子查询或其逻辑等效项。看看:blogs.oracle.com/sql/…
标签: sql oracle greatest-n-per-group