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
| -- solde progressif fact
with reqSoldeProgFact as (
select t1.date, t1.montant, t1.client, SUM(t2.montant) as soldeProgrFact
from testRelance t1 left join testRelance t2 on t1.date >= t2.date and t1.type = 'FAC' and t1.client = t2.client
where t1.type = 'FAC' and t2.type = 'FAC'
group by t1.date, t1.montant, t1.client
),
-- solde progressif regl
reqSoldeProgRegl as (
select t1.date, t1.montant, t1.client, SUM(t2.montant) as soldeProgrRegl
from testRelance t1 left join testRelance t2 on t1.date >= t2.date and t1.type = 'OD' and t1.client = t2.client
where t1.type = 'OD' and t2.type = 'OD'
group by t1.date, t1.montant, t1.client
),
reqSumRegl as (
select t1.date, t1.montant, t1.client, SUM(t2.montant) as soldeRegl
from testRelance t1 left join testRelance t2 on t1.date >= t2.date and t1.type = 'OD' and t1.client = t2.client
--where t1.type = 'OD'
group by t1.date, t1.montant, t1.client
),
reqSumFactClient as (
select client, coalesce (SUM(montant),0) as soldeFact
from testRelance
where type = 'FAC'
group by client
),
reqSumReglClient as (
select client, coalesce (SUM(montant),0) as soldeRegl
from testRelance
where type = 'OD'
group by client
)
select
t3.client,t3.numpiece, t3.montant, t3.date,t3.type,
reqSoldeProgFact.soldeProgrFact,
reqSoldeProgregl.soldeProgrRegl,
abs(coalesce(reqSumFactClient.soldeFact,0)) as SommeFact,
--reqSumRegl.*,
abs(coalesce(reqSumReglClient.soldeRegl,0)) as SommeRegl,
case
when t3.type = 'FAC' then
case when abs(coalesce(reqSumReglClient.soldeRegl,0)) >= soldeProgrFact then 0
when (abs(coalesce(reqSumReglClient.soldeRegl,0)) < soldeProgrFact) and (soldeProgrFact-abs(coalesce(reqSumReglClient.soldeRegl,0)) <= t3.montant) then soldeProgrFact-abs(coalesce(reqSumReglClient.soldeRegl,0))
else t3.montant
end
when t3.type = 'OD' then
case when coalesce(reqSumFactClient.soldeFact,0) >= coalesce(abs(soldeProgrRegl),0) then 0
when (coalesce(reqSumFactClient.soldeFact,0) < abs(soldeProgrRegl)) and (abs(soldeProgrRegl)-coalesce(reqSumFactClient.soldeFact,0) <= t3.montant) then abs(soldeProgrRegl)-coalesce(reqSumFactClient.soldeFact,0)
else t3.montant
end
end as Solde |
Partager