HiveQL:使用查询结果作为变量

5
在Hive中,我想动态地从一个表中提取信息,将其保存在变量中并进一步使用。考虑以下示例,在该示例中,我检索列var的最大值,并希望在后续查询中将其用作条件。
set maximo=select max(var) from table;

select
  *
from
  table
where
  var=${hiveconf:maximo}

尽管已经尝试,但它仍然无法正常工作。

set maximo=select max(var) from table;

${hiveconf:maximo}

shows me the intended result.

Doing:

select '${hiveconf:maximo}'

提供

"select max(var) from table"

though.

Best

2个回答

8
Hive将变量直接替换,而不执行它们。使用shell包装脚本将结果传递到变量中,并将其传递到您的Hive脚本中。
maximo=$(hive -e "set hive.cli.print.header=false; select max(var) from table;")
hive -hiveconf "maximo"="$maximo" -f your_hive_script.hql

在脚本中,您可以使用以下代码:select '${hiveconf:maximo}'

有没有办法从hue做到这一点?我想在视图中使用它。 - Hein du Plessis
@HeinduPlessis 很抱歉,我无法在Hue中做同样的事情。只能传递已经计算好的变量。使用“启用参数化”复选框、配置、添加key=varname,然后它会要求添加value。在查询中使用${varname}即可。 - leftjoin

1

@Hein du Plessis

虽然在Hue中无法完全实现您想要的操作——这一直是我感到沮丧的原因——如果您受限于使用Hue,不能像上面建议的那样使用shell包装器,则可以根据情况采用解决方法。

当我曾经想要通过选择表中列的最大值来设置变量以在查询中使用时,我像这样解决了它:

首先,我将结果放入一个由两列组成的表中,其中一列为(任意单词)“MAX_KEY”,另一列为最大计算结果,如下所示:

drop table if exists tam_seg.tbl_stg_temp_max_id;
create table tam_seg.tbl_stg_temp_max_id as
select
    'MAX_KEY' as max_key
    , max(pvw_id) as max_id
from
    tam_seg.tbl_dim_cc_phone_vs_web;

我在子查询中添加了单词'MAX_KEY',然后将其与上述表连接,以便在主查询中使用结果:

select
    -- *** here is the joined in value from the table being used ***
    cast(mxi.max_id + qry.temp_id as string) as pvw_id
    , qry.cc_phone_vs_web
from
    (
    select
        snp.cc_phone_vs_web
        , row_number() over(order by snp.cc_phone_vs_web) as temp_id
        -- *** here is the key being added to the sub-query ***
        , 'MAX_KEY' as max_key
    from
        (
        select distinct cc_phone_vs_web from tam_seg.tbl_stg_base_snapshots
        ) as snp
    left outer join
        tam_seg.tbl_dim_cc_phone_vs_web as pvw
        on snp.cc_phone_vs_web = pvw.cc_phone_vs_web
    where
        pvw.cc_phone_vs_web is null
    ) as qry
-- *** here is the table with the select result in being joined in ***
left outer join
    tam_seg.tbl_stg_temp_max_id as mxi
    on qry.max_key = mxi.max_key
;

不确定这是否符合您的情况,但也许可以适应。我99%确定您不能直接将选择语句放入Hue变量中。

如果我只是在Hue中做某些事情,我可能会使用临时表和连接方法。但如果我无论如何都要使用shall包装器,我肯定会在那里完成它。

希望这有所帮助。


是的,我也在使用Hue,真让人沮丧! - Hoang Minh Quang FX15045

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接