我尝试了许多oracle分析函数来实现我的需求但却无法实现。 这是一个简单的例子:
WITH W1 AS (
SELECT 100 key1, 0 key2, 0 key3, 'open' status, 'date1' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 1 key3, 'open' status, 'date2' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 2 key3, 'close' status, 'date3' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 3 key3, 'close' status, 'date4' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 4 key3, 'close' status, 'date5' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 5 key3, 'open' status, 'date6' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 6 key3, 'open' status, 'date7' date_column FROM DUAL )
SELECT W1.*,
CASE WHEN LAG(status,1) OVER(PARTITION BY key1,key2 ORDER BY key3) <> status THEN date_column
ELSE FIRST_VALUE(date_column) OVER (PARTITION BY key1,key2,status ORDER BY key3 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) END as DESIRED
FROM W1
ORDER BY 1,2,3
我正在尝试在状态更改时获得有序组的第一个值。 我只需要在DESIRED列上的最后一行应该是&#34; date6&#34;
你有什么建议吗? Oracle 11gr2
感谢。
答案 0 :(得分:0)
从Oracle 12c R1(12.1)开始,有一个行限制条款
你可以只使用FETCH FIRST 1 ROWS;
WITH W1 AS (
SELECT 100 key1, 0 key2, 0 key3, 'open' status, 'date1' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 1 key3, 'open' status, 'date2' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 2 key3, 'close' status, 'date3' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 3 key3, 'close' status, 'date4' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 4 key3, 'close' status, 'date5' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 5 key3, 'open' status, 'date6' date_column FROM DUAL UNION ALL
SELECT 100 key1, 0 key2, 6 key3, 'open' status, 'date7' date_column FROM DUAL )
SELECT W1.*,
CASE WHEN LAG(status,1) OVER(PARTITION BY key1,key2 ORDER BY key3) <> status THEN date_column
ELSE FIRST_VALUE(date_column) OVER (PARTITION BY key1,key2,status ORDER BY key3 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) END as DESIRED
FROM W1
ORDER BY 1,2,3
FETCH FIRST 1 ROWS ONLY;
请参阅文档https://oracle-base.com/articles/12c/row-limiting-clause-for-top-n-queries-12cr1