简体   繁体   中英

SAP Hana - SQL - calculate columns on the same table without recursive functions

I have the following simple table with approx. 40k items:

|date|consum|

Based on this table, I want to calculate some new columns. At the end, the table should looks like:

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

Unfortunately the SAP Hana Database does not support recursive table statements...

Here are the calculation rules:

  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 = select the consum from the row with the min value
  6. max = select the consum from the row with the max value

At the moment I have a stored precedure with 5 variables. In each variable I calculate i new coulmn. It is very very dirty... How can i make it different? I cant use recursive functions... :/

Here is my sql snippet... have fun =)

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;

You can use following CTE Common Table Expression in your SQLScript BTW, it is very interesting that nearly the same SQL Server CTE syntax matches the SAP HANA SQLScript syntax :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM