2016-08-30 39 views
0
來算唯一字符串

試想下表蜂巢SQL:如何通過preffix

text 
---- 
h 
he 
hel  // All above are prefixes 
helll123 // hel is a prefix of helll123; this is the first occurence of helll123 
helll123 // second helll123 
f 
fa 
fals 
falst0 // fals is a prefix of falst0 

下面的查詢是僞代碼來說明我是什麼之後

SELECT 
unique_by_prefix(text) AS unique_text, // pseudo code 
count(*) 
FROM 
my_table 
GROUP BY 1 

應該產生以下結果

unique_text count 
helll123  2 
falst0   1 

基本上,我們會忽略前綴並只計算唯一的文本。

+1

你怎麼能告訴這是一個前綴,這是一個字?應該有一些規則。 –

+0

我其實並沒有試圖去區分它是否是一個詞。我會更新這個問題。我會忽略任何前綴或其他東西 – samol

回答

0

窗函數 https://cwiki.apache.org/confluence/display/Hive/LanguageManual+WindowingAndAnalytics

select text, 
    lead(text) over (order by text) as next_text, 
    lag(text) over (order by text) as pre_text 
from my_table; 

的結果將是:

text next_text pre_text 
h  he  NULL 
he  hel  h 
hel helll123 he 
helll123 helll123 hel 
helll123 f helll123 
f  NULL helll123 

,那麼你可以用這些值進行比較:如果next_text文本開始,這個記錄是不是一個你想要的,否則得到這個記錄。

case when instr(next_text, text) = 1 then null else text as text_u_want 

然後取出空並加入MY_TABLE,你可以得到文字數

+0

令人驚歎!讓我嘗試 – samol

0

我不認爲你可以在Hive中用一個查詢來做到這一點。

這是一個可能性:

select text, count(*) 
from t 
where not exists (select 1 
        from t t2 
        where t2.text <> t.text and t2.text like t1.text || '%' 
       ) 
group by text; 

雖然這捕獲邏輯,我懷疑蜂巢希望對相關條款的平等。

0

這是一種做法。

  select distinct text into my_table1 from my_table 
      alter table my_table1 add sno int identity 

      create table my_table2 (text varchar(max), counter int) 

      declare @i int = 0 
      While (@i < (select COUNT(*) from my_table1)) 
      Begin 
      set @i = @i + 1 
      declare @text varchar(max) = (select text FROM my_table1 where sno = @i) 
      insert into my_table2 values(
      (select text from my_table1 where sno = @i), 
      (select COUNT(*) from my_table1 where text like @text + '%')) 
      End 

      select A.text, count(*) from my_table A left join my_table2 B on A.text = B.text where B.counter = 1 group by A.text