1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| WITH T AS (
SELECT 1 id_modele, 1 num_prototype, trunc(to_date('16/09/2012','DD/MM/YYYY')) DATE_MEC FROM dual union
SELECT 1 id_modele, 2 num_prototype, trunc(to_date('01/01/2012','DD/MM/YYYY')) DATE_MEC FROM dual union
SELECT 2 id_modele, 3 num_prototype, trunc(to_date('01/01/2013','DD/MM/YYYY')) DATE_MEC FROM dual union
SELECT 2 id_modele, 4 num_prototype, trunc(to_date('01/09/2012','DD/MM/YYYY')) DATE_MEC FROM dual union
SELECT 2 id_modele, 5 num_prototype, trunc(to_date('01/08/2012','DD/MM/YYYY')) DATE_MEC FROM dual
),
t_next as (
select id_modele, num_prototype, date_mec,
lead(num_prototype) over (partition by id_modele order by date_mec) as next_proto,
lead(date_mec) over (partition by id_modele order by date_mec) as next_date_mec
from t
)
select id_modele,
max(num_prototype) keep (dense_rank first order by case when date_mec <= trunc(sysdate)
then date_mec
end desc NULLS LAST) as Numproto_prec,
max(case when date_mec <= trunc(sysdate) then date_mec end) as dte_mec_prec,
min(next_proto) keep (dense_rank first order by case when coalesce(next_date_mec, to_date('31/12/9999','dd/mm/yyyy')) >= trunc(sysdate)
then coalesce(next_date_mec, to_date('31/12/9999','dd/mm/yyyy'))
end NULLS LAST) as Numproto_next,
min(case when next_date_mec >= trunc(sysdate) then next_date_mec end) as dte_mec_next
from t_next
group by id_modele |