sql server - SQL Query using value from previous row -


i trying subtract value of previous row current row using sql.

select      rd.ponum,      od.orderline,      rd.partnum,      p.partdescription,      od.ordernum,      rd.ourqty,      od.number01 reserved,      case when rd.ourqty - od.number01 > 0           od.number01           else rd.ourqty end allocated,      rd.ourqty - od.number01 newourqty,      c.custnum,      c.name dbo.rcvdtl rd inner join      dbo.part p on rd.partnum = p.partnum inner join      dbo.orderdtl od on rd.partnum = od.partnum inner join      dbo.orderhed oh on od.ordernum = oh.ordernum inner join      dbo.customer c on od.custnum = c.custnum (rd.ponum = 73)        , (od.number01 > 0)        , (od.openline = 1) 

this returns values:

ponum | orderline | partnum | partdescription | ordernum | ourqty | reserved | allocated | newourqty | custnum | name 73         1       10050926 example description    62       55         35         35          20         1032     sam test 73         1       10050926 example description    63       55         6          6           49         496     steve test 

but want return:

ponum | orderline | partnum | partdescription | ordernum | ourqty | reserved | allocated | newourqty | custnum | name 73         1       10050926 example description    62       55         35         35          20         1032     sam test 73         1       10050926 example description    63       55         6          6           14         496     steve test 

in row 1 newourqty= 20 (55-35). row 2 needs compute newourqty current row calculating newourqty (from row n-1) - reserved (from row n).

how can retrieve value previous row using sql?

edit

i using microsoft sql

maybe technique useful (here add value of row n value of row n-1):

create table test(     source int )  insert test values(1) insert test values(10) insert test values(20) insert test values(30) insert test values(40) insert test values(50)   /*here query*/ temp (       select t.*,row_number() on (order t.source) row_num       test t     )     select      x.source,     x.source + isnull((select y.source temp y y.row_num = x.row_num - 1),0)  sum_acumulate     temp x 

you can try here.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -