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

问题描述 投票:0回答:1

我在 hive CTE 中使用 row_number 窗口函数(with 子句)

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 块中生成,但似乎在使用时重新生成。

hive row-number
1个回答
0
投票

原因是CTE(Common Table Expressions)只是表达式,这意味着它只是像脚本一样,它不会具体化结果。我执行以下查询

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
© www.soinside.com 2019 - 2024. All rights reserved.