1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| drop table MyTable;
create table MyTable (Source varchar(10), polNb int, Ccy varchar(3), DtDebut datetime, Numero int);
insert into MyTable(Source, polNb, Ccy, DtDebut, Numero) select 's1', 1, 'EUR', '2015-03-15', null;
insert into MyTable(Source, polNb, Ccy, DtDebut, Numero) select 's1', 1, 'EUR', '2015-04-15', null;
insert into MyTable(Source, polNb, Ccy, DtDebut, Numero) select 's1', 1, 'EUR', '2017-06-15', null;
insert into MyTable(Source, polNb, Ccy, DtDebut, Numero) select 's1', 1, 'EUR', '2022-06-15', null;
insert into MyTable(Source, polNb, Ccy, DtDebut, Numero) select 's2', 1, 'EUR', '2016-03-15', null;
insert into MyTable(Source, polNb, Ccy, DtDebut, Numero) select 's2', 1, 'EUR', '2016-04-15', null;
insert into MyTable(Source, polNb, Ccy, DtDebut, Numero) select 's2', 1, 'EUR', '2018-06-15', null;
insert into MyTable(Source, polNb, Ccy, DtDebut, Numero) select 's2', 1, 'EUR', '2023-06-15', null;
WITH aggregate AS (
SELECT ALL Source, polNb, Ccy, MIN(DtDebut) AS MinDtDebut
FROM MyTable
GROUP BY 1, 2, 3
)
UPDATE MyTable AS m
INNER JOIN aggregate AS a ON (m.Source, m.polNb, m.Ccy) = (a.Source, a.polNb, a.Ccy)
SET m.Numero = TIMESTAMPDIFF(YEAR, a.MinDtDebut, m.DtDebut)
WHERE m.Numero = '' OR m.Numero IS NULL;
select * from MyTable; |
Partager