考虑具有基于具有以下逻辑结构的主键(id)的顺序的隐含层次结构的SQL Server 2017表(我们称其为Products):
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
select childid, item_type, max(parentId) as productid from (
select children.*, parents.id as parentId from (
select id as childId, Item_Type from products where Item_Type in ('SKU', 'RULE')
) children
inner join (
select id from products
where Item_Type in ('Product')
) parents
on parents.id < children.childId
) hierearchy
group by childid, item_type
order by childid
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'