首页 > 解决方案 > 如果table1中有特定行,如何编写插入table2的hive sql

问题描述

我面临一个蜂巢问题。

  1. 从 sql 之后我会得到一个 0 或 1

“从表 1 中选择计数(*),其中 ...”

  1. 如果结果为1,那么我将执行sql

“插入 table2 分区(d)(从表 1 中选择 xxxx,其中...按 t 分组)”

否则什么都不做。

我的问题是如何将这两个 sql 一起写成一个 sql。我只被允许写一个长的 sql。

我尝试将第一个sql放到sql2中的where条件中,但是它抛出了一个错误,说不支持在子查询中对table1进行操作(记不太清了,像这样)。

对于有经验的程序员来说,这听起来是一个非常简单的问题,但我刚开始学习 hive 2 天。

标签: hivehiveql

解决方案


如果插入覆盖表分区中的选择不返回行,则没有任何内容被覆盖。

因此,只需计算您在同一数据集中的计数并按其过滤,如果您想在插入之前聚合不同级别的数据,请使用分析功能

Insert Into table2 partition(d) 
select col1, col2, sum(col3), etc, etc, partition_col
from
(
select --some columns here,
       --Assign the same count to all rows
       count(case when your_boolean_condition then 1 else null end) over () as cnt
  from table 1
) s 
 where cnt=1 --If this is not satisfied, no overwrite will happen 
   AND more_conditions 
group by ...

另一种可能的方法是对您的计数使用交叉连接:

insert Into table2 partition(d) 
select xxxx ... ... ..., partition_column as d 
from 
(
select t.*, c.cnt
table1 t cross join (select count(*) cnt from table1 where condition) c
)s
where cnt=1 <and another_condition>

推荐阅读