2016-08-30 4 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

ハイブで1つのクエリでこれを行うことはできません。これは、ロジックをキャプチャしますが、私はハイブは相関句の平等を望んでいると思われる、

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; 

はここで1つの可能性です。

0

これを行う1つの方法があります。

  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