sql >> Base de Datos >  >> RDS >> Sqlserver

Cómo pivotar, vincular y agrupar una tabla con

Si tienes un número fijo de niveles

Ejemplo

Declare @YourTable Table ([Id] int,[Parent] int,[Name] varchar(50),[Level] int)
Insert Into @YourTable Values 
 (1,NULL,'Clinical',1)
,(2,NULL,'Custom',1)
,(3,NULL,'Medicare',1)
,(4,NULL,'Validation',1)
,(5,1,'Medicaid',2)
,(6,2,'CD',2)
,(7,3,'Specialty',2)
,(8,5,'Fraud',3)
,(9,2,'Institutional',3)
,(10,8,'Professional',4)

;with cteP as (
      Select Id
            ,Parent 
            ,PathID = cast(Id as varchar(500))
            ,PathNm = cast(name as varchar(500))
      From   @YourTable
      Where  Parent is null
      Union  All
      Select Id  = r.Id
            ,Parent  = r.Parent 
            ,PathID = cast(p.PathID+', '+cast(r.Id as varchar(25)) as varchar(500))
            ,PathNm = cast(p.PathNm+'||'+r.name as varchar(500))
      From   @YourTable r
      Join   cteP p on r.Parent  = p.Id)
Select B.*
      ,ID = A.PathID
 From  cteP A
 Cross Apply (
                Select Level1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
                      ,Level2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
                      ,Level3 = ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
                      ,Level4 = ltrim(rtrim(xDim.value('/x[4]','varchar(max)')))
                From  (Select Cast('<x>' + replace((Select replace(PathNm,'||','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as X 
             ) B
 Order by A.PathID

Devoluciones