【问题标题】:Finding the date before/after a date stored in int representation (Hive SQL)查找存储在 int 表示中的日期之前/之后的日期(Hive SQL)
【发布时间】:2022-01-25 04:03:37
【问题描述】:

我需要在以特定日期为中心的日期范围之间进行选择,但我的日期分区列存储为 int。

例如,在“20210901”之前和之后的日期之间进行选择(20210831 到 20210902)

有没有比我在下面想出的方法更简单的方法?

between cast(date_format(date_sub(date_format(from_unixtime(unix_timestamp(cast('20210901' as string),'yyyyMMdd')),'yyyy-MM-dd'),1),'yyyyMMdd') as int) and \
cast(date_format(date_add(date_format(from_unixtime(unix_timestamp(cast('20210901' as string),'yyyyMMdd')),'yyyy-MM-dd'),1),'yyyyMMdd');

【问题讨论】:

    标签: sql date hive casting timestamp


    【解决方案1】:

    unix_timestamp + from_unixtime 转换仅当您有一些日期格式无法使用字符串函数转换为 yyyy-MM-dd 格式时才需要,例如 1 Jan 21 。 unix_timestamp 和 from_unixtime 底层使用的 SimpleDateFormat 类比较繁重,一点也不简单,甚至 regexp_replace 更容易转换。

    尽可能使用字符串操作:

    select part_col between int(replace(date_sub(regexp_replace('20210901','^(\\d{4})(\\d{2})(\\d{2})$','$1-$2-$3'),1),'-',''))
                        and int(replace(date_add(regexp_replace('20210901','^(\\d{4})(\\d{2})(\\d{2})$','$1-$2-$3'),1),'-',''))
    

    即使Int() 转换不是必需的,Hive 也会隐式转换:

    select part_col between replace(date_sub(regexp_replace('20210901','^(\\d{4})(\\d{2})(\\d{2})$','$1-$2-$3'),1),'-','')
                        and replace(date_add(regexp_replace('20210901','^(\\d{4})(\\d{2})(\\d{2})$','$1-$2-$3'),1),'-','')
    

    如果你可以提供日期格式yyyy-MM-dd的参数,那就更简单了:

    select part_col between replace(date_sub('2021-09-01',1),'-','')
                        and replace(date_add('2021-09-01',1),'-','')
    

    【讨论】:

      【解决方案2】:

      你那里似乎有很多步骤。 我认为这应该能让你到达那里。仍然不是很漂亮,但对我来说确实更清楚了。

      WHERE
      from_Unixtime(unix_timestamp(cast (<integer date column> as string),'yyyyMMdd'), 'yyyy-MM-dd') BETWEEN
      date_add( from_Unixtime(unix_timestamp(cast (20210901 as string),'yyyyMMdd'), 'yyyy-MM-dd') ,-1) AND
      date_add( from_Unixtime(unix_timestamp(cast (20210901 as string),'yyyyMMdd'), 'yyyy-MM-dd') ,-1) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        • 1970-01-01
        • 1970-01-01
        • 2018-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多