Oracle SQL查询进程状态之间的时间

时间:2014-10-01 08:08:04

标签: sql database oracle

我在Oracle中有这个表:

Process| State | Date ;
 A| 0 | 19/09/14 ;
 A| 1 | 30/09/14 ;
 A| 2 | 31/09/14

使用日期列,您知道进程何时更改为相应的状态

我需要获得一个这样的表

Process | Time between state 0 and 1 | time between state 1 and 2

2 个答案:

答案 0 :(得分:0)

这会为您提供PROCESSCHANGE IN STATENUMBER OF DAYS

SQL> WITH DATA AS(
  2  SELECT 'A' PROCESS, 0 STATE, TO_DATE('19/09/14','dd/mm/rr') DT FROM DUAL UNION ALL
  3  SELECT 'A',         1,       TO_DATE('30/09/14','dd/mm/rr')    FROM DUAL UNION ALL
  4  SELECT 'A',         2,       TO_DATE('01/10/14','dd/mm/rr')    FROM DUAL)
  5  SELECT PROCESS,
  6    state
  7    ||' - '
  8    ||new_state change_in_state,
  9    NEW_DT-dt NUMBER_OF_DAYS
 10  FROM
 11    (SELECT A.*,
 12      LEAD(STATE) OVER(ORDER BY STATE, DT) NEW_STATe,
 13      LEAD(DT) OVER(ORDER BY STATE, DT) NEW_DT
 14    FROM DATA A
 15    )
 16  WHERE NEW_DT-dt IS NOT NULL
 17  /

PROCESS    CHANGE_IN_ NUMBER_OF_DAYS
---------- ---------- --------------
A          0 - 1              11
A          1 - 2               1

答案 1 :(得分:0)

假设进程必须通过状态0进行,则将1作为下一状态,将2作为下一状态;此查询使用LEAD()向前看1和2状态值(如果存在)

<强>查询

SELECT
       PROCESS
     , l1STATEDATE - STATEDATE   AS TIME_0_1
     , l2STATEDATE - L1STATEDATE AS TIME_1_2
FROM (

      SELECT
              PROCESS
            , STATE
            , STATEDATE
            --, lead(STATE,1)     over(partition by PROCESS ORDER BY STATEDATE) as l1STATE
            , lead(STATEDATE,1) over(partition by PROCESS ORDER BY STATEDATE) as l1STATEDATE
            --, lead(STATE,2)     over(partition by PROCESS ORDER BY STATEDATE) as l2STATE
            , lead(STATEDATE,2) over(partition by PROCESS ORDER BY STATEDATE) as l2STATEDATE
      FROM STATEINFO
     )
WHERE STATE = 0

<强>结果:

| PROCESS | TIME_0_1 | TIME_1_2 |
|---------|----------|----------|
|       A |       11 |        1 |

See the SQLFiddle demo


注意我使用了字段名称&#34; stateDate&#34;因为我不建议使用SQL关键字作为名称