Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Cara memutar, menautkan, dan mengelompokkan tabel dengan

Jika Anda memiliki jumlah level yang tetap

Contoh

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

Pengembalian




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Mengapa kueri SQL saya untuk menyisipkan baris tabel tidak berfungsi dengan benar?

  2. Cara PILIH [temp table1] =[subpilih 1], [temp table2] =[subpilih 2] DARI [Stored Procedure]

  3. Cara Membuat Tabel dengan Batasan Kunci Asing di SQL Server - Tutorial SQL Server / TSQL Bagian 66

  4. SQL Pivot Table dinamis

  5. Cara mendapatkan nilai kolom dalam SQL yang dipisahkan koma