2014-10-27 86 views
1

我們有'defs'表(定義爲TEXT,ref爲INT),其中def是單詞的定義,ref是對單詞的引用。刪除所有子字符串

目標:

我需要爲每個定義(DEF)刪除所有重複定義(這將被包含在一個最長的一個)

初始條件:

  1. 原料計數爲300000

  2. 定義長度可以是5 000個符號。

實施例:

DEFS:

  • 動物大耳 - 1

  • 動物大耳和大鼻子 - 1

  • 大動物與尾 - 1種

  • 小毛茸哺乳動物 - 2

  • 小毛皮哺乳動物灰色尾 - 2

輸出:

  • 動物與有點耳朵和大鼻子 - 1

  • 與灰尾巴毛茸茸的小哺乳動物 - 2

想法與哈希碼,但我不能完成我的想法:(

不知道如何把它做?

+0

您正在使用什麼版本的SQL Server?請不要使用'text'爲您的數據,它的棄用,現在僅向後兼容 – Lamak 2014-10-27 16:41:58

回答

2

會這樣的工作嗎?

declare @table table(def text, ref int); 

insert into @table 
values 
('Animal with bit ears', 1), 
('Animal with bit ears and big nose', 1), 
('Big animal with tail', 1), 
('Small furry mammal', 2), 
('Small furry mammal with gray tail', 2) 
; 

delete defs 
from (
    select row_number() over (
      partition by ref order by DATALENGTH(def) desc 
      ) rank_ 
    from @table 
    ) defs 
where defs.rank_ > 1; 

select * from @table; 
+0

這真棒!適用於我。謝謝! – 2014-10-27 16:55:02

+0

需要注意的是,如果兩行具有「def」相等的數據長度,那麼將任意選擇一個。如果這不是你想要的,你可以使用'rank'而不是'row_number'。 – Will 2014-10-27 16:58:27

+0

如果它的正確答案,你可以考慮將其標記爲正確的答案。 – Will 2014-10-28 18:18:23