简体   繁体   中英

How can I sort based on a next record field in SQL Server?

I have a table that includes a key field, a following key, and up to two previous keys. How can I create a result that is sorted based on the next record being equal to the following key?

KEY,PRKEY1,PRKEY2,FLWKEY   
-------------------------------
3701401,0000000,0000000,3701403
3701403,3701401,0000000,3701421
3701402,0000000,0000000,3701404
3701404,3701402,0000000,3701421
3701421,3701404,3701403,3701405
3701405,3701421,0000000,3701423
3701299,0000000,0000000,3701210
3701210,3701299,0000000,3702007
3702007,3701210,0000000,3701005
3701005,3702007,0000000,3701423
3701423,3701405,3701005,3701411
3701413,0000000,0000000,3701411
3701411,3701423,3701413,3701431
3701431,3701411,3701005,3701455
3701451,0000000,0000000,3701455
3701455,3701431,3701451,3701443
3701443,3701455,0000000,3701445
3701445,3701443,0000000,3701432
3701432,3701445,0000000,3701434
3701434,3701432,0000000,3701435
3701435,3701434,0000000,0000000

Result should look like:

KEY,PRKEY1,PRKEY2,FLWKEY
-------------------------------    
3701401,0000000,0000000,3701403
3701403,3701401,0000000,3701421
3701421,3701404,3701403,3701405
3701405,3701421,0000000,3701423
3701423,3701405,3701005,3701411
3701411,3701423,3701413,3701431
3701431,3701411,3701005,3701455
3701455,3701431,3701451,3701443
3701443,3701455,0000000,3701445
3701445,3701443,0000000,3701432
3701432,3701445,0000000,3701434
3701434,3701432,0000000,3701435
3701435,3701434,0000000,0000000

Thanks in advance. I only have about 50k records to sort out this way.

WITH    q (key, prkey1, prkey2, flwkey, init, lvl) AS
        (
        SELECT  *, key, 1
        FROM    mytable
        WHERE   key = 3701401
        UNION ALL
        SELECT  mt.*, q.init, q.lvl + 1
        FROM    q
        JOIN    mytable mt
        ON      mt.key = q.flwkey
        )
SELECT  key, prkey1, prkey2, flwkey
FROM    q
ORDER BY
        init, lvl

It's a linked list which you need to traverse in a recursive CTE.

sqlfiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM