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
| WITH t (Id, RefFact, RefMp) AS
(
SELECT 1, 'fact1', 'MP1' union all
SELECT 2, 'fact2', 'MP2' union all
SELECT 3, 'fact2', 'MP3' union all
SELECT 4, 'fact2', 'MP4' union all
SELECT 5, 'fact3', 'MP4' union all
SELECT 6, 'fact3', 'MP5' union all
SELECT 7, 'fact4', 'MP6' union all
SELECT 8, 'fact5', 'MP7'
)
, CTest AS
(
select Id as IdDeb, Id, RefFact, RefMp, 1 as Cpt,
cast(Id as varchar(max)) as pth
from t
union all
select c.IdDeb, t.Id, t.RefFact, t.RefMp, c.Cpt + 1,
c.pth + '-' + cast(t.Id as varchar(max))
from t
inner join CTest as c
on c.RefFact = t.RefFact
or c.RefMp = t.RefMp
where charindex(cast(t.Id as varchar(max)), c.pth) = 0
)
select Id, RefFact, RefMp,
dense_rank() over(order by min(IdDeb)asc) as numDossier
from CTest
group by Id, RefFact, RefMp
order by Id asc;
Id RefFact RefMp numDossier
----------- ------- ----- --------------------
1 fact1 MP1 1
2 fact2 MP2 2
3 fact2 MP3 2
4 fact2 MP4 2
5 fact3 MP4 2
6 fact3 MP5 2
7 fact4 MP6 3
8 fact5 MP7 4 |