gpt4 book ai didi

sql - 如何根据 SQL Server 中的下一个记录字段进行排序?

转载 作者:行者123 更新时间:2023-12-04 05:24:14 25 4
gpt4 key购买 nike

我有一个表,其中包含一个键字段、一个后续键和最多两个前面的键。如何创建基于下一条记录等于以下键排序的结果?

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

结果应如下所示:
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

提前致谢。我只有大约 50k 条记录可以通过这种方式进行整理。

最佳答案

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

这是一个需要在递归 CTE 中遍历的链表。

sqlfiddle here

关于sql - 如何根据 SQL Server 中的下一个记录字段进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13387595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com