【问题标题】:How to form Management Hierarchy Formation in SQL Server?如何在 SQL Server 中形成管理层次结构?
【发布时间】:2021-04-07 01:38:07
【问题描述】:

如何形成以下记录的管理层次?

输入数据:

Id Sub ID Name Description
101 NULL Page Reference Page Reference
102 1 Page 1 Page 1
103 2 Ashok Ashok
104 3 Kumar Kumar
105 4 Page 2 Page 2
106 5 Arvind Arvind
107 4 Page 11 Page 11
108 6 Gova Gova
109 7 Gokul Gokul
110 8 Kannan Kannan

我尝试使用递归 CTE,但找不到确切的解决方案。需要以下格式, 条件是

New Leaf ID --> If Sub ID IS NULL , then it will be 1 , If contains page row, it will be 2, if contains other than that it will be 3.

Page --> Whenever Page row starts, from the next row original information showing for that page. we need to form based on the lead rows. 

输出数据:

Id Sub ID Name Page New Leaf ID
101 NULL Page Reference 1
102 1 Page 1 Page 1 2
103 2 Ashok Page 1 3
104 3 Kumar Page 1 3
107 4 Page 11 Page 11 2
108 6 Gova Page 11 3
109 7 Gokul Page 11 3
110 8 Kannan Page 11 3
105 4 Page 2 Page 2 2
106 5 Arvind Page 2 3

【问题讨论】:

    标签: sql sql-server sql-server-2012 case gaps-and-islands


    【解决方案1】:

    新的叶子 id 是条件逻辑。至于页面,它有点棘手:似乎行的顺序定义了依赖关系,所以基本上你希望将每个级别 3 的叶子与前面的级别 2 相关联。

    这是一种使用窗口计数来识别属于同一页面的叶子的方法:

    select id, subid, name, 
        case when sub_id is not null
            then max(case when name like 'Page %' then name end) over(order by id) 
        end as page,
        case 
            when subid is null then 1
            when name like 'Page %' then 2
            else 3
        end as new_leaf_id
    from (
        select t.*,
            sum(case when name like 'Page %' then 1 else 0 end) over(order by id) grp
        from mytable t
    ) t
    

    【讨论】:

    • 如果我们使用 id 排序,我认为当我用于对 Page 列进行排序时它将不起作用。
    • @arvindgova:请尝试对您的数据进行查询,看看它是如何工作的。
    • 它不工作。在 Page 列中它只显示 1.
    猜你喜欢
    • 2019-08-10
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多