Oracle SQL查询从日志表中获取数据

时间:2015-07-27 04:49:26

标签: sql oracle oracle11g

以下提供的数据是巨大日志表的微小快照。 请帮我查询以识别具有TRAN_ID的451140014和440102253的记录。

记录的状态从“实际”更新为“确定”。 根据我们的应用程序的业务规则,它不会发生,我需要获取这个状态正在更新的巨大表中的所有记录的列表。

ROW_ID        TRAN_ID      TRAN_DATE                 CHG_TYPE    DB_SESSION    DB_OSUSER    DB_HOST     STAT_CD
500-XNEGXU    451327759    7/24/2015 11:35:26 AM    Update     SBLDATALOAD     siebelp       pas01      Actual
500-XNEGXU    451299279    7/24/2015 10:13:18 AM    Update     SBLDATALOAD     siebelp       pas01      Actual
500-XNEGXU    451140014    7/24/2015 1:04:36 AM     Update      SBLDATALOAD     siebelp      pas01      Definite
500-XNEGXU    440102253    6/23/2015 3:10:33 PM     Update      SBLDATALOAD     convteam     pas01      Actual
500-XNEGXU    426245149    5/8/2015 2:11:21 PM      Update       SBLDATALOAD     convteam    pas11      Actual

修改: 非常感谢您的帮助。几乎没有修改您的查询以获得单行结果。这会给我下一个交易ID,它将状态从“实际”翻转为“确定”

select row_id, tran_id, next_tran_id,tran_date, next_tran_date,stat_cd
  from (
    select abc.*, lag(tran_id) over (order by tran_id desc) next_tran_id,lag(tran_date) over (order by tran_id desc) next_tran_date,
        case when stat_cd='Actual' and (lag(stat_cd) over (partition by row_id order by tran_id desc)) = 'Definite' then 1 
        end change
      from abc )
  where change = 1 order by row_id, tran_id

1 个答案:

答案 0 :(得分:0)

此查询使用函数lead()Definite的顺序显示stat_cd为tran_id的所有行和前一行:

select row_id, tran_id, tran_date, stat_cd 
  from (
    select data.*, 
        case when stat_cd='Definite' 
               or (lead(stat_cd) over (order by tran_id)) = 'Definite' then 1 
        end change
      from data )
  where change = 1 order by row_id, tran_id

SQLFiddle demo

如果您的数据以这种方式组织,则可能需要将over (order by tran_id)更改为over (partition by row_id order by tran_id)

编辑:在提供其他信息后修改了查询:

select row_id, tran_id, tran_date, stat_cd 
  from (
    select xyz.*,
        case 
          when stat_cd='Actual'   
               and (lead(stat_cd) over (order by tran_id)) = 'Definite' then 1 
          when stat_cd='Definite' 
               and (lag(stat_cd)  over (order by tran_id)) = 'Actual'   then 2 
        end change
      from xyz)
  where change is not null

SQLFiddle demo