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
| ; With MaTable (id_client, quantite, date_achat) as
(
select 1, 23, '1983-09-14' union all
select 1, 22, '1995-01-12' union all
select 1, 21, '2002-06-06' union all
select 1, 145, '2004-06-11' union all
select 1, 23, '2011-08-11' union all
select 2, 25, '1983-09-10' union all
select 2, 22, '1995-01-12' union all
select 2, 21, '1997-01-12' union all
select 2, 145, '2002-06-06' union all
select 2, 23, '2011-08-11'
)
select t1.id_client, t1.quantite, t1.date_achat
, sum(t2.quantite) as cumul
, min(t2.date_achat) as date_min_date_achat
, min(t1.date_achat) over(partition by t1.id_client, sign(sum(t2.quantite)-200)) as premiere_date
from MaTable as t1
inner join MaTable as t2
on t2.id_client = t1.id_client
and t2.date_achat <= t1.date_achat
group by t1.id_client, t1.quantite, t1.date_achat
having sum(t2.quantite) >= 200
order by t1.id_client asc, t1.date_achat asc
id_client quantite date_achat cumul date_min_date_achat premiere_date
----------- ----------- ---------- ----------- ------------------- -------------
1 145 2004-06-11 211 1983-09-14 2004-06-11
1 23 2011-08-11 234 1983-09-14 2004-06-11
2 145 2002-06-06 213 1983-09-10 2002-06-06
2 23 2011-08-11 236 1983-09-10 2002-06-06 |
Partager