【问题标题】:SQL join/merge two hierarchyid tablesSQL连接/合并两个hierarchyid表
【发布时间】:2017-12-20 13:17:20
【问题描述】:

有没有办法在 SQL Server 中加入/合并两个分层表?

我有两个示例表:BOMComponentDetail

declare @BOM table 
    (
      BomNode hierarchyid primary key,
      ComponentID int
    )

insert into @BOM 
values
    ('/',             NULL),
    ('/1/',           1),
    ('/1/1/',         2),
    ('/1/2/',         3),
    ('/1/3/',         4)

declare @ComponentDetail table
   (
       CompNode hierarchyid primary key,
       ComponentID int,
       SteelProductID int
   )

insert into @ComponentDetail 
values
   ('/',          NULL,NULL),
   ('/1/',        2, NULL),
   ('/1/1/',      2,1),
   ('/1/2/',      2,2)

我想做的是暂时合并这两个表,以便在我的应用程序中查看结果:

更新:@Sean Lange 我在声明 Result 表时犯了一个错误 - 它应该如下所示:

insert into @Result 
    values 
       ('/',     NULL, NULL),
       ('/1/',   1, NULL),
       ('/1/1/',   2, NULL),
       ('/1/1/1/', NULL, 1),
       ('/1/1/2/', NULL, 2),
       ('/1/2/',   3, NULL),
       ('/1/3/',   4, NULL)

select 
    Node.ToString() as NodeChar, ComponentID, SteelProductID 
from @Result

这是所需输出的图表: Output diagram

有人吗?

【问题讨论】:

  • 如果您不将单个记录 ID 值存储为列中的“正斜杠分隔”(?) 值,会容易得多。您可以使用递归 CTE 轻松地将 BOM 的所有级别拼凑在一起。有了这个,看起来您必须首先解析数据并对其进行规范化,然后使用另一个查询来返回您需要的数据。
  • @JacobH 不是分隔数据,OP 使用的是 hierarchyid 数据类型。 docs.microsoft.com/en-us/sql/t-sql/data-types/…
  • 啊,这很好。从未使用hierarchyid 类型。每天学习新东西。

标签: sql sql-server join merge hierarchyid


【解决方案1】:

您可以将这两个表连接在一起,就像其他任何表一样。在这种情况下,您可能想要一个完整的外部连接。

这会从您的示例数据中返回您想要的输出:

select Node = coalesce(b.BomNode.ToString(), c.CompNode.ToString())
    , ComponentID = coalesce(b.ComponentID, c.ComponentID)
    , c.SteelProductID
from @BOM b
full outer join @ComponentDetail c on c.CompNode = b.BomNode

--编辑--

根据我的新理解,我认为它是这样的(但它在层次结构上不太正确,但我不清楚你想要什么):

select distinct Node = coalesce(b.BomNode.ToString(), c.CompNode.ToString()) + coalesce(convert(varchar(4), c.ComponentID) + '/', '')
    , ComponentID = coalesce(b.ComponentID, c.ComponentID)
    , c.SteelProductID
from @BOM b
full outer join @ComponentDetail c on b.ComponentID = c.ComponentID 

【讨论】:

  • 感谢 Sean 的回答,不幸的是,结果并非如此。根据您的查询,我得到了模棱两可的输出:ibb.co/mUz6Pm,这是不正确的。
  • 您可能想加入 ComponentID。但我对你想要的输出有点困惑。 '/4/' 来自哪里?它在您的示例数据中不存在。
  • /4/ 来自 BOM 表(节点号:/1/3/)。我想将它们加入到 ComponentID 上,并在这个特定的示例中加入 ComponentID = 2。BOM 表包含装配/零件依赖项,但某些组件可能包含 SteelProducts 以及我可以从 ComponentDetail 获得的信息。我为我的英语道歉:)
  • 我在结果表中犯了一个错误 - 查看问题:)
  • 差不多了:ibb.co/jVceS6 - SteelProductID=2 应该在 1/1/2/ 节点而不是 1/2/2/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 2012-05-01
  • 1970-01-01
相关资源
最近更新 更多