SQL自联接发现层次结构

问题描述 投票:-1回答:2

考虑具有基于具有以下逻辑结构的主键(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
sql-server join grouping hierarchy
2个回答
0
投票
我想我想出了一个解决方案。可能不是最好的方法,但它似乎可以充分发挥作用:

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


0
投票
标量函数也可能很方便

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'

© www.soinside.com 2019 - 2024. All rights reserved.