【问题标题】:How to get the last non empty value of a hierarchy?如何获取层次结构的最后一个非空值?
【发布时间】:2023-03-09 03:48:01
【问题描述】:

我有一个层次结构,每个级别都有适当的值,比如说:


A               100
  A1            NULL
  A2            NULL
B
  B1            NULL
  B2            1000
      B21       500 
      B22       500
  B3            NULL

这个层次结构在我的数据库中实现为父子层次结构


Hierarchy Table
------------------------
Id       Code      Parent_Id
1          A          NULL
2          A1          1
3          A2          3
4          B          NULL
5          B1          4
6          B2          4
7          B21         6
8          B22         6
9          B3          4

这是我的事实表:


Fact Table
------------------------
Hierarchy_Id          Value
1                      100
6                      1000
7                      500
8                      500

我的问题是:您知道/知道如何仅获取我的层次结构的最后一个非空值吗? 我知道有一个 MDX 函数可以完成这项工作,但我想以另一种方式完成这项工作。

明确地说,所需的输出是:


Fact Table
------------------------
Hierarchy_Id          Value
1                      100
7                      500
8                      500

(如果需要的话,扁平化层次的工作已经完成了……)

提前谢谢你!

【问题讨论】:

    标签: sql hierarchy flatten


    【解决方案1】:

    如果您的层次结构的代码是正确的,那么您可以使用代码中的信息来确定层次结构的深度。我认为您想过滤掉任何以它开头的较长代码的“代码”。

    在这种情况下:

    select f.*
    from fact f join
         hierarchy h
         on f.hierarchyId = h.hierarchyId
    where not exists (select 1
                      from fact f2 join
                           hierarchy h2
                           on f2.hierarchyId = h2.hierarchyId
                      where h2.code like concat(h.code, '%') and
                            h2.code <> h.code
                     )
    

    这里我使用了函数concat() 来创建模式。在某些数据库中,您可能会改用+||

    【讨论】:

    • 感谢您的回答,但我无法根据代码进行查询。但是如果你认为层次结构的深度我可以在层次结构表中添加一列。
    • @stormblow 。 . .真可惜,因为问题包括代码,而且非常有用。生成代码需要高度依赖数据库的迭代或递归查询。深度不够,需要整个层次结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    相关资源
    最近更新 更多