首页 > 解决方案 > SQL 在 ID 列表中选择顶部 parentId,如果所有顶部 parentId 相同,则返回行

问题描述

我必须编写我想合并为一个的脚本:

SELECT [CategoryId] FROM [dbo].[Unit] where Id in (716,724) 

DECLARE @Id INT = 15

;WITH cteGetRootID
As
(

    SELECT
        Id, [Name], ParentId, 1 AS CodePosition
    FROM
        Category WHERE Id = @Id
    UNION All
    SELECT
        ic.Id, ic.[Name], ic.ParentId, CodePosition + 1
    FROM Category ic
    INNER JOIN cteGetRootID cte ON ic.Id = cte.ParentId
)
SELECT  top 1 Id, [Name]  FROM cteGetRootID
ORDER BY CodePosition desc

我想对第一部分中的所有结果执行低代码,如果所有结果都具有相同的 Root,则返回 Root Catogry Like DECLARE @Id INT = SELECT [CategoryId] FROM [dbo].[Unit] where Id in (716,724)

希望有意义

标签: sqlsql-serverjoin

解决方案


您可以在第一次选择并集时使用joinbetweendbo.Unit和:dbo.Category

;WITH cteGetRootID
As
(
    SELECT
        c.Id, c.[Name], c.ParentId, 1 AS CodePosition
    FROM
        Category c 
            INNER JOIN  [dbo].[Unit] u on u.CategoryID = c.Id
    WHERE u.Id in (716,724) 
    UNION All
    SELECT
        ic.Id, ic.[Name], ic.ParentId, CodePosition + 1
    FROM Category ic 
             INNER JOIN cteGetRootID cte ON ic.Id = cte.ParentId
)
SELECT  top 1 Id, [Name]  FROM cteGetRootID
ORDER BY CodePosition desc

推荐阅读