我有下面的更新表……
| 参考|事件日期|列详细信息|事件类型|cat1|
| --------------|--------------|--------------|--------------|--------------|
| 二|昨天|ABC|第三型|猫X|
| 二|上周|abc3|十一型|B类|
| 二|今日|abc123|第四型|猫A|
| 二|上月|xyz|二十二式|Z轴|
| 二|去年|世界电视联合会|十一型|Z轴|
所以for refer = 2
abc123是基于最新日期的最新更新。
abc 3是event_type 11和cat = b的最新更新
xyz是cat z的最新更新
是否可以在一个查询中完成此操作?我可以得到我的结果的唯一方法是使用单独的查询或CTE的:
with cte1 as (
select t.refer,
t.detail
from
(
select ch.refer,
ch.detail,
row_number() over (partition by refer order by event_date desc) as rn
from table ch
) as latest
where ch.rn = 1
)
cte2 as(
select t.refer,
t.detail
from
(
select ch.refer,
ch.detail,
row_number() over (partition by refer order by event_date desc) as rn
from table ch
where event_type = '11'
and cat = 'b'
) as latest
where ch.rn = 1
)
cte3 as(
select t.refer,
t.detail
from
(
select ch.ref,
ch.detail,
row_number() over (partition by refer order by event_date desc) as rn
from table ch
where event_type = 'z'
) as latest
where ch.rn = 1
and cat = 'z'
);
2条答案
按热度按时间xzv2uavs1#
我们可以用三个
row_number
来枚举三个分区,然后用条件聚合来透视:fiddle
当然,这是假设您将日期存储为类似
date
的数据类型,而不是像'today'
或'last year'
这样的字符串。或者,如果您希望结果以行而不是列的形式显示,那么我们不需要聚合:
t2a7ltrp2#
您可以使用
UNION
(当同一日期出现在多个选择中时删除重复):结果:
Demo here