2016-06-17 7 views
1

以下のデータを見ると、同じリーフの下の上位レベルに存在するIDを簡単に見つけることができます。重複するノードをSQL Server階層から削除する

など。 ID 4,5は、行4,5,8,9および12,13に存在する。 同じIDが階層(行8,9)のさらに下に存在するので、行4,5を削除したいが、行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/ 
+0

12と13は別々の葉にあります(どういう意味ですか?)? 12と13は8と9の共通の祖先を共有しています(つまり、両方とも/ 1と/ 1/2 /の両方から派生しています)。私は難しくしようとはしていない。私はこの問題を理解しようとしています。 –

答えて

0

たとえばmaxの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 
     ) 
0

これは、それが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; 

OUTPUT

id keeper deletethis 
4 8  4 
5 9  5 
関連する問題