![](/img/trans.png)
[英]Substring to Get value only after first occurrence of : in Oracle SQL
[英]Oracle SQL - Returning row of first occurrence by value
我有以下格式的數據:
ID YRMTH EVENT
1 201201 0
1 201202 0
1 201203 1
1 201204 0
1 201205 0
2 201304 0
2 201305 0
2 201306 0
3 201301 0
3 201302 0
3 201303 0
3 201304 1
3 201305 0
我想返回每個ID帶有YRMTH和EVENT的行。 如果發生了EVENT(= 1),那么我想要事件發生時的YRMTH並且EVENT =1。如果沒有發生EVENT(= 0),那么我想返回YRMTH和EVENT = 0中列出的最后一個月。
在此示例中,我需要以下輸出:
ID YRMTH EVENT
1 201203 1
2 201306 0
3 201304 1
本質上,此查詢的目的是確定事件發生的第一個月(如果一個事件完全發生的話)。 如果沒有發生任何事件,那么我只想要我們有數據的最后一個月。
我以為我需要使用窗口函數( PARTITION BY
),但是我願意接受任何可能的解決方案。
您可以通過聚合來做到這一點。 不需要解析函數:
select id,
(case when max(event) = 1 then min(case when event = 1 then yrmth end)
else max(yrmth)
end) as yrmth,
max(event) as event
from table t
group by id;
嘗試這個:
with cte as
(select id,
case event
when 1 then yrmth
else max(yrmth) over (partition by id order by yrmth)
end as yrmth,
event,
row_number() over
(partition by id
order by case event when 1 then 1 else 0 end desc, yrmth desc) as rn
from your_table)
select id, yrmth, event
from cte
where rn = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.