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



在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}

向我展示了预期的结果。

操作:

select '${hiveconf:maximo}'

给出

"select max(var) from table"

不过。

最佳

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}'

@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%确信你不能直接将select语句放入Hue中的变量中。

如果我只是在Hue中做一些事情,我可能会做临时表和联接方法。但如果我用的是shall包装纸,我肯定会在那里做。

我希望这能有所帮助。

最新更新