配置单元sql通过表循环比较值

配置单元sql通过表循环比较值,sql,hive,Sql,Hive,我在蜂房里有一张桌子,看起来像下图 fruit value apple 2 apple 3 apple 4 plum 2 plum 3 plum 4 我想在表中循环,比较前面的值和果数,并基于循环创建一个新列(total)。这就是逻辑 if [fruit] = previous[fruit] then total = prev[fruit] 新桌子

我在蜂房里有一张桌子,看起来像下图

fruit           value
apple           2
apple           3
apple           4
plum            2
plum            3
plum            4
我想在表中循环,比较前面的值和果数,并基于循环创建一个新列(total)。这就是逻辑

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
如何在配置单元中使用SQL实现这一点? 此外,我还对查询中的结果进行了排序,以便其按结果和升序值分组的SQL表表示无序集。除非列指定了顺序,否则没有“上一行”。假设您有这样一个列,那么您可以使用
lag()

是指定排序的列的名称。

SQL表表示无序集。除非列指定了顺序,否则没有“上一行”。假设您有这样一个列,那么您可以使用
lag()


是指定排序的列的名称。

添加到前面的答案中,您可以通过如下方式写入临时表来人工创建订单:

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

这将在原始表中重新创建顺序,并允许您执行Gordon上面所说的操作。除了前面的答案之外,您还可以通过如下方式写入临时表来人为创建顺序:

create table #holding (rowid int identity, fruit varchar(max), value int)
insert #holding
select fruit, value from your table
order by fruit, value
这将在原始表中重新创建顺序,并允许您执行上面Gordon所说的操作