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

Cara paling sederhana untuk melakukan self-join rekursif?

WITH    q AS 
        (
        SELECT  *
        FROM    mytable
        WHERE   ParentID IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate
        UNION ALL
        SELECT  m.*
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q

Dengan menambahkan kondisi pemesanan, Anda dapat mempertahankan urutan pohon:

WITH    q AS 
        (
        SELECT  m.*, CAST(ROW_NUMBER() OVER (ORDER BY m.PersonId) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    mytable m
        WHERE   ParentID IS NULL
        UNION ALL
        SELECT  m.*,  q.bc + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.PersonID) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q
ORDER BY
        bc

Dengan mengubah ORDER BY syaratnya kamu bisa mengubah urutan saudara.



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Basis Data + Otentikasi Windows + Nama Pengguna/Kata Sandi?

  2. SYSDATETIME() Contoh di SQL Server (T-SQL)

  3. menentukan set karakter dari tabel / database?

  4. Apakah praktik buruk NOLOCK (Petunjuk Sql Server)?

  5. Cara Menghapus Spasi Leading dan Trailing di SQL Server – TRIM()