sql-server - SQL 自联接发现层次结构
问题描述
考虑一个 SQL Server 2017 表(我们称之为产品),它具有基于主键 (id) 排序的隐含层次结构,具有以下逻辑结构:
Product (root)
- SKU (optional children)
- Rule (optional children)
示例表可能如下所示:
ID Item_Type
1 Product
2 SKU
3 SKU
4 SKU
5 Rule
6 Rule
7 Product
8 Rule
9 Rule
10 Product
11 SKU
鉴于我想查找每个 SKU 和规则的父产品,什么是合适的查询?结果应该是这样的:
ID Item_Type ProductId
2 SKU 1
3 SKU 1
4 SKU 1
5 Rule 1
6 Rule 1
8 Rule 7
9 Rule 7
11 SKU 10
解决方案
标量函数也很方便
CREATE FUNCTION FindParentKey
(
@CurrentItemKey int
)
RETURNS int
AS
BEGIN
return (
SELECT MAX(ID)
FROM Product
WHERE ID < @CurrentItemKey and Item_Type = 'Product'
)
END
GO
SELECT ID, Item_Type, dbo.FindParentKey(ID)
FROM Product
WHERE Item_Type <> 'Product'
推荐阅读
- java - 如何在不丢失原始文件的情况下压缩图像?
- angular - 需要根据地图函数中的条件进行过滤
- azure - 如何在交叉订阅中复制 Azure sql db
- function - Delphi - 如果没有创建类,为什么这个函数起作用?
- c - 如何将数据保存在已知内存位置一次以便在 x86 程序集中多次重用?
- extjs - Sencha Touch 部署选项?
- rest - 带有 ID 令牌的 REST API Firestore 身份验证
- api - 为什么 System.Net.WebException:错误:发生 SecureChannelFailure?
- python - 如何在多个条件下断言一次?
- google-apps-script - 用于 Google Apps 脚本的 JWT?