【问题标题】:Restructure a query in Impala/Hive that is using subquery to create new column in table重组 Impala/Hive 中使用子查询在表中创建新列的查询
【发布时间】:2020-04-14 09:31:57
【问题描述】:

我正在将 SQL 查询转换为 Impala。 SQL 查询在 select 中使用子查询来创建新列,如下 -

select *, (select min(day)
           from date_series 
           where day > t.work_day) as next_work_day
from table1 t

但是,Impala 不支持在 select 中创建新列的子查询,并且此查询失败。能否请我帮助以 Impala 可以执行的方式重写此查询。

查询目的:为work_day 列查找下一个工作日。

Table1 是外部表,包含

table1 contains 4 columns including the work day column

date_series contains all working dates stating from 2019-06-18 to current_day + 5点赞

   2019-06-20
   2019-06-21
   2019-06-24
   .
   .

【问题讨论】:

  • 请提供样本数据、期望的结果以及您想要做什么的解释。

标签: sql subquery impala


【解决方案1】:

我认为你可以这样做:

select t.*, ds.next_day
from table1 t left join
     (select ds.*, lead(day) over (order by day) as next_day
      from date_series ds
     ) ds
     on t.current_work_day >= ds.day and
        (t.current_work_day < ds.next_day or ds.next_day is null);

【讨论】:

  • 嗨,戈登,感谢您的回复和建议。我的 impala 中的前导函数是在前导列和相应的日期列中给出一个值“2019-06-20”。 ` Day --- --- Lead(day) 2019-06-20 2019-06-20 2019-06-20 2019-06-20 `
  • @ShriyaGupta 。 . .只有在date_series 中有重复项时才会发生这种情况。
  • 这真的很有帮助。它奏效了,非常感谢:)
【解决方案2】:

你可以重写你的查询如下

select 
    t.*,
    work_day 
from table1 t 
join (
    select 
        min(day) as work_day 
    from date_series
) ds
on t.current_work_day = ds.work_day

where ds.work_day > t.current_work_day

【讨论】:

  • 您好 Zealous,上面的代码只会为右表产生一个结果,即 date_series 中的最小值。我正在尝试的是在外部表中的 work_day 列的系列中获得下一天。因此,对于 work_day 列中的每个值,我都希望在日期系列表中的第二天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多