当CTE中的窗口函数row_number在hive中生成结果时,

z6psavjg  于 4个月前  发布在  Hive
关注(0)|答案(1)|浏览(44)

我在配置单元CTE(with子句)中使用row_number窗口函数

with data(
    select 1 a,1 b
union select 1,2
union select 1,3
union select 1,4
...
union select 1,26
),
data_with_row_num (
select a,b,row_number() over(partition by 1) as rn from data
)
select * from data_with_row_num
union all 
select * from data_with_row_num

字符串
我认为row_number应该在CTE块中生成固定的id,我将临时表(data_with_row_num)合并了两次,并期望得到具有相同rn的相同b。

a b rn
1 4 1
1 2 1
1 9 2
1 3 2
...
1 19 26
1 24 26


似乎相同的rn有不同的B,我的问题是为什么会发生这种情况。我认为rn应该在with块中生成,但似乎它在使用时重新生成。

lyfkaqu1

lyfkaqu11#

原因是CTE(公共表表达式)只是表达式,这意味着它只是像脚本一样的东西,它不会具体化结果。

with data(
    select 1 a,1 b
),
data_with_rn (
select a,b,rand(10)  from data
)
select * from data_with_rn
union all 
select * from data_with_rn

字符串
并且结果被

a b EXPR$2
1 1 0.9514867562334854
1 1 0.9771762097973918


随机得到不同的结果,如果真的需要具体化临时结果,缓存表(在spark中)可能是一个解决方案

cache table data select 1 a,1 b;
cache table data_with_rn select a,b,rand(10)  from data;
select * from data_with_rn
union all 
select * from data_with_rn

相关问题