【问题标题】:What is the HiveQL for obtaining day of week?获取星期几的 HiveQL 是什么?
【发布时间】:2015-07-06 10:52:18
【问题描述】:

我从我的表“推文”中选择日期为

select to_date(created_at) from tweets;

这给了我这样的日期,

2011-09-28
2011-09-25
2011-09-25
2011-09-24

但是,我需要将日期转换为星期几格式, 1 代表星期一,2 代表星期二,以此类推。

我如何做到这一点?

编辑: 我想我可以将日期作为示例日期,

select from_unixtime(unix_timestamp('2014-01-12','yyyyMMdd'),'u');

如何将其合并到我的原始查询中?

【问题讨论】:

    标签: hive hiveql


    【解决方案1】:

    date_format(..., 'u') 对于类似日期的字符串/类型给出 Monday=1 等等。

    另一个答案使用 'w' 表示一年中的星期,这不是你想要的。

    您的原始查询变为:

    SELECT date_format(created_at, 'u') from tweets;

    请参阅java docs 了解所有选项。

    【讨论】:

      【解决方案2】:

      如果您有 hive 1.2,这应该可以工作。它在语言手册中。我正在运行 hive 0.13,所以我无法测试 date_format 函数,但它应该给你一个 1 - 7 的整数;

      select cast(date_format('2015-04-06'),'w' as int) as DOW from table;
      

      我在 hive 0.13 上对此进行了测试:

      select from_unixtime(unix_timestamp('2015-07-06','yy-MM-dd'),'u') as 
         DOW from table;
      

      这导致 1,所以它似乎工作。

      如果上述失败,可以使用的其他选项是:

      select from_unixtime(unix_timestamp('2015-07-06','yy-MM-dd'),'EEEE') as 
         DOW from table;
      

      这将返回“星期一”

      另外

      select from_unixtime(unix_timestamp('2015-07-06','yy-MM-dd'),'EEE') as 
         DOW from table;
      

      将返回“星期一”

      然后您可以简单地做一个案例何时更改为整数。

      case when DOW = 'Mon' then 1 
           when DOW = 'Tue' then 2
           -- ...
           when DOW = 'Sat' then 6
          else 7
      end as day_of_week
      

      不要使用这个:

      select pmod(datediff('2015-07-06','1970-01-04'),7) + 1 as DOW from table;
      

      这个返回2,不正确,有人建议过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 2013-12-31
        • 2017-11-07
        • 2015-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多