Forum Stats

  • 3,769,695 Users
  • 2,253,008 Discussions
  • 7,875,155 Comments

Discussions

How can I sum the previous row with LAG() function?

Edisson Gabriel López
Edisson Gabriel López Member Posts: 33 Green Ribbon

Best regards,

I am using the following function (LAG) to sum the previous row: 

(LAG(INV_FINAL, 1, 0) OVER (PARTITION BY DISTRIBUIDORA ORDER BY PERIODO ASC) + LAG(INV_FINAL, 2, 0) OVER (PARTITION BY DISTRIBUIDORA ORDER BY PERIODO ASC)) + INV_FINAL AS RESULT

But it is not giving me the expected result as can you see:

The correct result should be :

I am attentive to your comments, I would be very grateful if you can help me, thank you.

Best Answer

  • Paulzip
    Paulzip Member Posts: 8,494 Blue Diamond
    Accepted Answer

    You probably want something like this (untested as not near DB) :

    sum(result) over (partition by distribuidora order by periodo asc rows between unbounded preceding and current row) rows_sum

    Edisson Gabriel López

Answers