簡體   English   中英

Hive SQL通過表比較值循環

[英]Hive sql loop through table comparing values

我在蜂巢中有一張桌子,看起來像下面

fruit           value
apple           2
apple           3
apple           4
plum            2
plum            3
plum            4

我想遍歷表並比較先前的值和水果,然后根據循環創建一個新的列(總計)。 這將是邏輯

if [fruit] = previous[fruit] then total = prev[fruit]

新表應如下所示

fruit       value      total
apple       2    
apple       3          2
apple       4          3
plum        2        
plum        3          2
plum        4          3

如何在Hive中使用SQL實現此目的? 我也已在查詢中對結果進行了排序,因此按水果和升序分組

SQL表表示無序集。 除非有列指定順序,否則沒有“上一個”行。 假設您有這樣一列,則可以使用lag()

select t.*,
       lag(value) over (partition by fruit order by ?) as prev_value
from t;

? 是用於指定順序的列的名稱。

除了前面的答案外,您還可以通過寫入臨時表來人為地創建訂單,如下所示:

create table #holding (rowid int identity, fruit varchar(max), value int)
insert #holding
select fruit, value from your table
order by fruit, value

這將在原始表中重新創建訂單,並允許您執行上面的戈登所說的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM