【问题标题】:SQL Self-Join Discover HierarchySQL 自联接发现层次结构
【发布时间】:2019-09-29 04:08:52
【问题描述】:

考虑一个 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

【问题讨论】:

  • 您所说的“物理订购”是什么意思?除了 ORDER BY 的(部分)排序之外,没有其他方法可以按任何顺序获取行。所以不清楚你在问什么。另外,这表明没有研究。当明确时,这可能是一个常见问题解答。代码问题也需要minimal reproducible example。将单词放在吓人的引号中并不能清楚地说明您没有写出的特殊特定含义。请参阅How to Askhelp center 和投票箭头鼠标悬停文本。
  • 更新了物理顺序以表示主键顺序。我会在这里发布一些研究样本,但都是垃圾。

标签: sql-server join grouping hierarchy


【解决方案1】:

我想我找到了解决方案。可能不是最好的方法,但它似乎表现得足够好:

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

【讨论】:

    【解决方案2】:

    标量函数也可以很方便

    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'
    

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 2011-08-27
      • 2020-11-30
      相关资源
      最近更新 更多