问题
I need a solution to find the nearest date value for missing values based on date.Suppose I have a temporary table like below with columns Product Date Value
Product Date Value
P1 1/10 10
P1 2/10 20
P1 3/10
P1 4/10
Here you find that for date 3/10 and 4/10 there are no values and it should copy the values from the nearest date that is 2/10 to 3/10 and 4/10 i.e 20. I used the lag function in HANA and it is copying the value only for 3/10 and for date 4/10 it is null. Is there any function in HANA which can take the value from the nearest date value like kind of Repetitive LAG.
I don't want to do cursor and CTEs are not supported in SQL script as far as I know
BR Arshad
回答1:
Could you please check following SQLScript statement for SAP HANA database
select
Product, Date, Value
from (
select
pv.Product,
pv.Date,
ifnull(pv.Value, p.Value) as Value,
row_number() over (partition by pv.Product, pv.Date order by p.Date desc) as rn
from ProductValue pv
left join ProductValue p
on
pv.Value is null and
p.Product = pv.Product and
p.Date < pv.Date and
p.Value is not null
) t
where rn = 1
order by
Product,
Date
I used a self-join in combination with ROW_NUMBER() function in WHERE clause
Output of above SAP HANA SQL script is as follows
来源:https://stackoverflow.com/questions/47028803/nearest-date-value