1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
-- crétion d'un jeu d'essai avec deux comptes
with tab(cpt, dte, mnt) as
(select 'C1', cast('2024-01-02' as date), 5000 union all
select 'C1', cast('2024-01-05' as date), 6000 union all
select 'C1', cast('2024-01-06' as date), 6500 union all
select 'C2', cast('2024-01-01' as date), 1500 union all
select 'C2', cast('2024-01-04' as date), 2100 union all
select 'C2', cast('2024-01-06' as date), 1800
)
-- création d'un calendrier de quelques dates contigues
, cal(dte, seq) as
(select min(dte)
, 1
from tab
union all
select dateadd(day, 1, dte)
, seq + 1
from cal
where seq < 10
)
-- combinaison de toutes les dates pour tous les comptes
, dtx (cpt, dte) as
(select distinct
tab.cpt
, cal.dte
from tab
cross join cal
)
-- et enfin, requête pour "boucher les trous" (reprise du montant de la date qui précède)
select * from (
select dtx.cpt as compte
, dtx.dte as datex
, case when tab.mnt is not null then tab.mnt
else (select T1.mnt
from tab T1
where T1.cpt = dtx.cpt
and T1.dte = (select max(dte)
from tab T2
where T2.cpt=T1.cpt
and T2.dte<dtx.dte
)
)
end as montant
from dtx
left join tab
on tab.cpt=dtx.cpt
and tab.dte=dtx.dte
where dtx.dte <= (select max(dte) from tab)
) subq
where subq.montant is not null
order by 1, 2 |
Partager