【问题标题】:Remove Duplicate Nodes from SQL Server Hierarchy从 SQL Server 层次结构中删除重复节点
【发布时间】:2016-06-17 08:47:53
【问题描述】:

查看下面的数据是否有一种简单的方法可以找到同一叶子下更高级别的 ID 并将其删除。

例如ID 4,5 存在于第 4,5、8,9 和 12,13 行中。 我想删除第 4,5 行,因为相同的 ID 存在于层次结构的更下方(第 8,9 行),但第 12,13 行保留在单独的叶子上。

Rows to be Removed

row ID  Path
1   1   /1/
2   2   /1/2/
3   3   /1/2/3/
4   4   /1/2/3/4/
5   5   /1/2/3/5/
6   6   /1/2/3/6/
7   7   /1/2/3/6/7/
8   4   /1/2/3/6/4/
9   5   /1/2/3/6/5/
10  8   /1/2/8/
11  7   /1/2/8/7/
12  4   /1/2/8/4/
13  5   /1/2/8/5/

【问题讨论】:

  • 12 和 13 在单独的叶子上(你的意思是分支吗?)如何? 12 和 13 与 8 和 9 共享一个共同的祖先(也就是说,它们都派生自 /1/ 和 /1/2/)。我不是想变得困难;我正在尝试理解问题。

标签: sql sql-server sql-server-2008 hierarchy


【解决方案1】:

最大 ID len = 1 的示例

select *
--delete t1
    from table as t1
    where exists(
            select *
                from table as t2
                where left(t2.path, len(t1.path - 2)) = left(t1.path, len(t1.path - 2))
                    and charindex(right(t1.path, 2), t2.path, len(t1.path)) > 0
        ) 

【讨论】:

    【解决方案2】:

    这是我的方法,它应该适用于任何长度的 ID:

    with 
    conversed as (
    select substring(reverse(path),CHARINDEX('/',reverse(path),2), len(path)-CHARINDEX('/',reverse(path),2)) inverse_path, id, t.row
      from t)
    select c.id, c.row keeper, c1.row deletethis  
      from conversed c join conversed c1 
        on c.id = c1.id 
       and c.row <> c1.row
       and c.inverse_path like '%' +c1.inverse_path;
    

    输出

    id  keeper  deletethis
    4   8       4
    5   9       5
    

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 1970-01-01
      • 2019-08-10
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多