我有这样的东西
Date Group ID
11/01 'A' 1
12/01 'A' 2
13/01 'B' 3
14/01 'B' 4
我基本上想要的是例如从'A'组获得最新消息
Date Group ID LatestID_from_GROUP_A_ordered_by_recent_date
11/01 'A' 1 2
12/01 'A' 2 2
13/01 'B' 3 2
14/01 'B' 4 2
或至少是这样的
Date Group ID LatestID_from_GROUP_A_ordered_by_recent_date
11/01 'A' 1 null
12/01 'A' 2 null
13/01 'B' 3 2
14/01 'B' 4 2
答案 0 :(得分:1)
如何?
with demo (somedate, somegroup, id) as
( select date '2018-01-11', 'A', 1 from dual union all
select date '2018-01-12', 'A', 2 from dual union all
select date '2018-01-13', 'B', 3 from dual union all
select date '2018-01-14', 'B', 4 from dual union all
select date '2018-01-15', 'A', 5 from dual -- example from comments
)
select somedate, somegroup, id
, ( select max(id) keep (dense_rank last order by somedate)
from demo
where somegroup = 'A' ) as last_a
from demo;
SOMEDATE SOMEGROUP ID LAST_A
----------- --------- ---------- ----------
11/01/2018 A 1 5
12/01/2018 A 2 5
13/01/2018 B 3 5
14/01/2018 B 4 5
15/01/2018 A 5 5
请注意,如果有多行最后一个日期,则max(id)
只能是决胜局。
答案 1 :(得分:0)
逻辑似乎是:
select t.*,
max(case when group = 'A' then id end) over (order by date) as latest_from_a
from t;
以上内容获取每个日期的累计最大值。如果您想要整体最大值:
select t.*,
max(case when group = 'A' then id end) over () as latest_from_a
from t;
答案 2 :(得分:0)
戈登快要在那里了。
您想在整个查询中创建一个窗口,但只选择'A'的最大值:
select
t.*,
max(case when group = 'A' then id end) over (partition by 1) as latest_from_a
from t
“按1划分”将创建一个完整结果集的窗口,因为它仅按一个静态值进行分组:1.