查找单表链中的最后一条记录 (SQL Server)

发布于 2024-09-19 09:40:18 字数 416 浏览 3 评论 0原文

在 SQL Server 2005 中得到了这张表,它用于维护合并操作的历史记录:

  • Column FROM_ID (int)
  • Column TO_ID (int)

现在我需要一个查询,该查询将原始 FROM_ID 作为输入,并返回最后一个可用的 TO_ID。

例如:

  • ID 1 合并到 ID 2
  • 稍后,ID 2 合并到 ID 3
  • 再一次,ID 3 合并到 ID 4

所以我试图组合在一起的查询将作为输入(在 WHERE 子句中)我推测)ID 1,并且应该给我最后一个可用的 TO_ID 作为结果,在本例中为 4。

我想我需要一些递归逻辑,但真的不知道如何开始。

谢谢 !

马蒂厄

Got this table in SQL Server 2005, which is used to maintain a history of merging operations:

  • Column FROM_ID (int)
  • Column TO_ID (int)

Now I need a query that takes the original FROM_ID as input, and returns the last available TO_ID.

So for instance:

  • ID 1 is merged to ID 2
  • Later on, ID 2 is merged to ID 3
  • Again later, ID 3 is merged to ID 4

So the query I'm trying to put together will take as input (in the WHERE clause I presume) ID 1, and should give me the last available TO_ID as a result, in this case 4.

I suppose I need some recursion logic, but don't really know how to start.

Thanks !

Mathieu

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

余厌 2024-09-26 09:40:18

使用 CTE 可以。

测试脚本

DECLARE @IDs TABLE (
  FromID INTEGER
  , ToID INTEGER
)

INSERT INTO @IDs
SELECT           1, 2 
UNION ALL SELECT 2, 3
UNION ALL SELECT 3, 4

SQL语句

;WITH q AS (
    SELECT  FromID, ToID
    FROM    @IDs
    UNION ALL 
    SELECT  q.FromID, u.ToID
    FROM    q
            INNER JOIN @IDs u ON u.FromID = q.ToID
)
SELECT  FromID, MAX(ToID)
FROM    q
WHERE   FromID = 1
GROUP BY
        FromID           

Using a CTE would work.

Testscript

DECLARE @IDs TABLE (
  FromID INTEGER
  , ToID INTEGER
)

INSERT INTO @IDs
SELECT           1, 2 
UNION ALL SELECT 2, 3
UNION ALL SELECT 3, 4

SQL Statement

;WITH q AS (
    SELECT  FromID, ToID
    FROM    @IDs
    UNION ALL 
    SELECT  q.FromID, u.ToID
    FROM    q
            INNER JOIN @IDs u ON u.FromID = q.ToID
)
SELECT  FromID, MAX(ToID)
FROM    q
WHERE   FromID = 1
GROUP BY
        FromID           
他夏了夏天 2024-09-26 09:40:18

如果这对你有用,请给 Lieven 接受的答案,因为它是基于他的代码。

;WITH q AS (
    SELECT  1 AS LEVEL, FromID, ToID
    FROM    @IDs
    WHERE FromID=1
    UNION ALL 
    SELECT  LEVEL + 1, q.FromID, u.ToID
    FROM    q
            INNER JOIN @IDs u ON u.FromID = q.ToID
)

SELECT TOP 1 ToID
 FROM q
ORDER BY LEVEL DESC

If this works for you give Lieven the accepted answer as it is based on his code.

;WITH q AS (
    SELECT  1 AS LEVEL, FromID, ToID
    FROM    @IDs
    WHERE FromID=1
    UNION ALL 
    SELECT  LEVEL + 1, q.FromID, u.ToID
    FROM    q
            INNER JOIN @IDs u ON u.FromID = q.ToID
)

SELECT TOP 1 ToID
 FROM q
ORDER BY LEVEL DESC
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文