【问题标题】:How to count unique integers in a string using hive?如何使用 hive 计算字符串中的唯一整数?
【发布时间】:2016-10-10 21:16:20
【问题描述】:

试图计算字符串中的唯一字节数?

DATA(例如只有数字字节的电话​​号码):

1234567890
1111111112

结果:

10
2

我已经尝试了以下方法,但它不起作用,因为我认为 sum() 不会接受 UDF 'if'。

 select phone
 , sum(
        cast(if(length(regexp_replace(phone,'0',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'1',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'2',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'3',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'4',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'5',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'6',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'7',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'8',''))<10,'1','0') as int) +
        cast(if(length(regexp_replace(phone,'9',''))<10,'1','0') as int)         
       )  as unique_bytes
 from table;

我也不反对正则表达式作为解决方案。

【问题讨论】:

    标签: sql regex hadoop hive


    【解决方案1】:

    使用 + 。 . .但像这样:

    select phone,
           ((case when phone like '%0%' then 1 else 0 end) +
            (case when phone like '%1%' then 1 else 0 end) +
            (case when phone like '%2%' then 1 else 0 end) +
            (case when phone like '%3%' then 1 else 0 end) +
            (case when phone like '%4%' then 1 else 0 end) +
            (case when phone like '%5%' then 1 else 0 end) +
            (case when phone like '%6%' then 1 else 0 end) +
            (case when phone like '%7%' then 1 else 0 end) +
            (case when phone like '%8%' then 1 else 0 end) +
            (case when phone like '%9%' then 1 else 0 end) +
           ) as ints
     from table;
    

    您的代码有几个问题:

    • sum() 是聚合函数,不需要。
    • if() 正在返回字符串,但您将这些值相加。
    • 我不确定您为什么使用regexp_replace() 而不仅仅是replace()

    【讨论】:

    • 戈登,感谢您的快速回复。根本不需要等式中的总和。我几乎是在我选择进入后立即意识到的。但是,您的解决方案正在走一条更好的道路,而且效率更高!谢谢。
    • 我在发帖时立即注意到了总和问题。傻我。 'if' 部分确实返回一个字符串,这就是我将其转换为整数的原因。至于使用 regexp_replace 代替替换,我使用了很多正则表达式并且只是默认为习惯。再次感谢您的解决方案。它肯定比我的效率更高,我希望我见过它。干杯。
    【解决方案2】:
        with tab1 as (
    select stack(3,
    '1','1234567890',
    '2','1111111112',
    '3','2222222223') as (col0, col1))
    select tab1.col0, count(distinct tf.col) from tab1 lateral view explode(split(tab1.col1,'')) tf as col
    where tf.col regexp '\\d'
    group by tab1.col0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 2015-09-14
      相关资源
      最近更新 更多