SAP Hana - SQL - 在没有递归函数的情况下计算同一个表上的列

时间:2016-11-30 15:14:57

标签: sql sap hana

我有以下简单表格。 40k物品:

|date|consum|

基于此表,我想计算一些新列。最后,该表应如下所示:

|date|consum|row|row_relativ|min|max|upper|lower|

不幸的是,SAP Hana数据库不支持递归表语句......

以下是计算规则:

  1. row = row_number() over(order by dates)
  2. row_relative = row*35040/32768
  3. min = floor(row_relative)
  4. max = ceil(row_relative)
  5. min =从最小值
  6. 行中选择消耗
  7. max =从具有最大值
  8. 的行中选择消费

    目前我有5个变量的存储过程。在每个变量中,我计算新的coulmn。它非常脏......我怎么能让它与众不同?我不能使用递归函数......:/

    这是我的sql片段......玩得开心=)

    var1 = select *, row_number() over(order by dates) as row from XYZ order by dates limit 34944;
    var2 = select *, (row * 34944/32768) as row_relative from :var1;
    var3 = select *, floor(row_relative) as min, ceil(row_relative) as max from :var2;
    
    var4 = select 
        p.*,
        (select consumfrom :var3 where row = p.min) as lower,
        (select consumfrom :var3 where row = p.max) as upper
    from :var3 p;
    
    var5 = select 
        p.*,
        (p.lower* (1-p.row_relative+p.min)+p.upper * (p.row_relativ - p.min)) as new_consum
    from :var4 p;
    

1 个答案:

答案 0 :(得分:0)

您可以在SQLScript中使用以下CTE Common Table Expression 顺便说一句,非常有趣的是,几乎相同的SQL Server CTE语法与SAP HANA SQLScript语法相匹配:)

with cte as (
select
    date,
    consum,
    row_number() over (order by date) as row
from rawdata
)
select
    date,
    consum,
    row,
    row * 35040 / 32768 as row_relative,
    floor( (row * 35040 / 32768) ) as min,
    ceil( (row * 35040 / 32768) ) as max,
    (select cte2.consum from cte cte2 where row = floor( (cte.row * 35040 / 32768) ) ) as min2,
    (select cte2.consum from cte cte2 where row = ceil( (cte.row * 35040 / 32768) ) ) as max2
from cte