sql - 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)
希望有意义
解决方案
您可以在第一次选择并集时使用join
betweendbo.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
推荐阅读
- c++ - C++ 中的 3d 全局数组
- python - 如何向 Python Shell 命令添加参数?
- python - 使用 selenium 查找属性的值
- css - 在 displayFlex 中具有绝对位置和 translateY 的位置(DropDown 项)
- java - 在没有行检索的情况下执行 MongoTemplate.aggregate
- javascript - 如何从数据绑定foreach javascript中获取元素
- elasticsearch - 解析字段失败,有弹性
- r - 创建一个新变量,标记 R 中绝对值变化的每个实例
- swift - 如何创建一个合适的 HStack,其对象之间的空间相等
- javascript - 有没有办法使用 Hyperledger Fabric 生成的公钥/私钥来加密文件/字符串?