does anyone have suggestions for this problem? i am trying to use oracle SQL to consolidate spans of effective_dt to expiration_dt where values in col_a, col_b, and col_c remain constant, but only for consecutive records where there is no change in any of the 3 columns in between.
if it helps, it is safe to assume that the effective date of the next record (by employee) is equal to the previous record plus 1 day.
i tried with min(), max() and group by, but the problem is the scenario below will return 12/1-12/31. then i tried with lead() function, but the problem is i do not know in advance how many records i will need to consolidate.
assume that i can get the data into the form below:
+----------+--------------+---------------+---------+---------+---------+
| employee | effective_dt | expiration_dt | col_a | col_b | col_c |
+----------+--------------+---------------+---------+---------+---------+
| 0001 | 12/1/2012 | 12/4/2012 | value_a | value_a | value_a |
| 0001 | 12/5/2012 | 12/6/2012 | value_a | value_a | value_a |
| 0001 | 12/7/2012 | 12/10/2012 | value_a | value_a | value_a |
| 0001 | 12/11/2012 | 12/17/2012 | value_a | value_b | value_a |
| 0001 | 12/18/2012 | 12/31/2012 | value_a | value_a | value_a |
+----------+--------------+---------------+---------+---------+---------+
expected result:
+----------+--------------+---------------+---------+---------+---------+
| employee | effective_dt | expiration_dt | col_a | col_b | col_c |
+----------+--------------+---------------+---------+---------+---------+
| 0001 | 12/1/2012 | 12/10/2012 | value_a | value_a | value_a |
| 0001 | 12/11/2012 | 12/17/2012 | value_a | value_b | value_a |
| 0001 | 12/18/2012 | 12/31/2012 | value_a | value_a | value_a |
+----------+--------------+---------------+---------+---------+---------+
attempt 1:
SELECT employee,
MIN(effective_dt),
MAX(expiration_dt),
col_a,
col_b,
col_c
FROM
(SELECT employee, effective_dt, ... FROM table_x, table_y, ... where...
) table_a
GROUP BY employee,
col_a,
col_b,
col_c;
attempt 2:
SELECT employee,
effective_dt,
lead(expiration_dt, 1) over (partition BY employee, col_a, col_b, col_c order by effective_dt) expiration_dt,
col_a,
col_b,
col_c
FROM
(SELECT employee, effective_dt, ... FROM table_x, table_y, ... where...
) table_a;
thank you!
In case we can, as you state, safely assume that next record equals previous record + 1 day, then we can chain these records up:
SQL Fiddle
Oracle 11g R2 Schema Setup:
Query 1:
Results: