Oracle-连续获取第一行

时间:2018-10-01 16:35:22

标签: sql oracle select

我想提取所有状态为“ A”的行,并提取状态为“ A”之后的每个帐户的第一行。 例如:

id   account   status
 1      X         A
 2      Y         C
 3      Y         A
 4      X         B
 5      X         C
 6      Y         C
 7      X         A
 8      X         C
 9      X         C
 ...

预期输出为

 1      X         A
 3      Y         A
 4      X         B
 6      Y         C
 7      X         A
 8      X         C
 ...

我该怎么办?

2 个答案:

答案 0 :(得分:5)

您可以使用lag函数“回头看”上一行。不幸的是,您不能在where子句中使用窗口函数,因此必须使用子查询:

SELECT id, account, status
FROM   (SELECT id, account, status,
               LAG(status) OVER (PARTITION BY account ORDER BY id ASC) AS prev_status
        FROM   mytable) t
WHERE  'A' IN (status, prev_status)

答案 1 :(得分:1)

在Oracle 12.1或更高版本中,MATCH_RECOGNIZE可以快速完成此类分配。 WITH子句只是用来提供测试数据(在尝试解决方案之前将其删除)。

with
  test_data(id, account, status) as (
    select 1, 'X', 'A' from dual union all
    select 2, 'Y', 'C' from dual union all
    select 3, 'Y', 'A' from dual union all
    select 4, 'X', 'B' from dual union all
    select 5, 'X', 'C' from dual union all
    select 6, 'Y', 'C' from dual union all
    select 7, 'X', 'A' from dual union all
    select 8, 'X', 'C' from dual union all
    select 9, 'X', 'C' from dual
  )
select id, account, status
from   test_data
match_recognize(
  partition by account
  order by     id
  all rows per match
  pattern      ( A X? )
  define       A as status = 'A',
               X as status is null or status != 'A'
)
order by id  -- if needed
 24  ;

    ID ACCOUNT STATUS
---------- ------- -------
     1 X       A
     3 Y       A
     4 X       B
     6 Y       C
     7 X       A
     8 X       C

6 rows selected.