Oracle – Calculating Time Elapsed

oracletime

I need to calculated time elapsed for each user to perform his part in a transaction.

The sequence is: 0 -1 – B2 or 0-B3
The table looks like the following:

+--------+--------+-------------------+------------------+-----------+
| id     | Trtype |Internal Status    | Timestamp        | User Name |
+--------+--------+-------------------+------------------+-----------+
|2072499 | BSE100 | 0                 | 03/06/2014 13:33 | User1     |
|2072499 | BSE100 | 1                 | 04/06/2014 08:53 | User2     |
|2072499 | BSE100 |B2                 | 03/06/2014 13:33 | User3     |
|2072605 | BSE100 | 0                 | 03/06/2014 13:33 | User1     |
|2072605 | BSE100 |B3                 | 03/06/2014 13:33 | User3     |
.....................

I am using the following sql query to generate the table above:

select h.id, h.trtype, T.DESCRIPTION, hist.internal_status,
 ts.description status_Desc, h.val_dte, h.account_dte, 
 hist.signature_timestamp, usr.login_name as user_name
  from k$transaction_header h, k$transtypes t, k$transaction_history hist, k$usr usr, K$TRANSACTION_STATUS ts
 where h.trtype = t.trtype
 and hist.trans_id = h.id
 and usr.id=hist.signature_usr
 and ts.id=hist.internal_status
 AND H.ACCOUNT_DTE = TO_DATE(&DATE_YYYYMMDD, 'yyyymmdd')
 order by h.id, hist.internal_status

Best Answer

Try this. Logically it's a self-join.

WITH transaction_user_parts AS
(
   select h.id, h.trtype, T.DESCRIPTION, hist.internal_status,
   ts.description status_Desc, h.val_dte, h.account_dte, 
   hist.signature_timestamp, usr.login_name as user_name
    from k$transaction_header h, k$transtypes t, k$transaction_history hist, k$usr usr, K$TRANSACTION_STATUS ts
   where h.trtype = t.trtype
   and hist.trans_id = h.id
   and usr.id=hist.signature_usr
   and ts.id=hist.internal_status
   AND H.ACCOUNT_DTE = TO_DATE(&DATE_YYYYMMDD, 'yyyymmdd')
)
SELECT  t1.id
      , t1.internal_status || ' -> ' || t2.internal_status internal_status_change
      , t2.user_name
      , (t2.signature_timestamp - t1.signature_timestamp) time_elapsed
FROM transaction_user_parts t1
JOIN transaction_user_parts t2
  ON (t1.id = t2.id
       AND t1.signature_timestamp <= t2.signature_timestamp
       AND (
             (t1.internal_status='0' AND t2.internal_status='1')
            OR
             (t1.internal_status='1' AND t2.internal_status='B2')
            OR
             (t1.internal_status='0' AND t2.internal_status='B3')
           )
      );