Search code examples
sqlhqlpresto

How to return a value from a calculation in the same column over the next partition


How do I do this within SQL?

Hi there, I'm new to Stack Overflow and I'm wondering how I do the above using a SQL query (or HQL).

I need to fill Column_1 with the results of the first row from column 1 into the following row and subsequently.

I hope my video has helped you to understand my question as I have run out of words to try explaining it.

*I do not have a code to start with as I could not come up with anything.

Thanks!


Solution

  • What you want is sort of cumulative product, which can be achieved using logarithm and exponential rules Which state that log(a * b) = log(a) + log(b) and e^log(a) = a.

    select t.*,
        exp(sum(ln(c)) over (order by date_col)) column_1
    from (
        select t.*,
            case when row_number() over (order by date) = 1 then 100 else column_2 end as c
        from your_table t
        ) t