/ Published in: SQL
Use this logic to avoid double counting in ORACLE SQL
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
SQL> SELECT * FROM t; START END_D ID ----- ----- ---------- 10:00 10:45 1 10:30 11:45 1 12:30 12:45 1 12:40 13:01 1 10:10 10:20 1 12:35 13:20 1 10:00 10:45 2 10:55 11:00 2 10:00 10:30 2 9 ROWS selected. SQL> SELECT 2 -- case when start_dat between lgs and lge then lge else start_dat end start_dat, 3 -- end_dat, 4 id, 5 SUM(24 * 60 * (end_dat - CASE WHEN start_dat BETWEEN lgs AND lge THEN lge ELSE start_dat END)) diff 6 FROM ( 7 SELECT id, start_dat, 8 lag(start_dat) OVER (partition BY id ORDER BY start_dat) lgs, 9 lag(end_dat) OVER (partition BY id ORDER BY start_dat) lge, 10 end_dat 11 FROM ( 12 SELECT id, start_dat, 13 lag(start_dat) OVER (partition BY id ORDER BY start_dat) lgsi, 14 lag(end_dat) OVER (partition BY id ORDER BY start_dat) lgei, 15 end_dat 16 FROM t 17 ) 18 WHERE end_dat > lgei OR lgsi IS NULL 19 ) 20 GROUP BY id 21 / ID DIFF ---------- ---------- 1 155 2 50
URL: http://www.experts-exchange.com/Database/Oracle/Q_22861266.html