Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

SQL Server - Calculate current row value using previous row value

I have following table and using SQL Server 2008

    Tbl_TRNSACTION

 RowNum    Transaction Type        InQty     OutQty     InPrice
    1              IN               20          0           20
    2              IN               50          0           40
    3              OUT              0           10          - 
    4              IN               10          0           30

I expect output in following format

If TransType is IN,

then (InQty*InPrice) is added in CumulativeStockVal

and StockRate = (CumulativeStockVal / Balance).

If Transaction Type is OUT,

then (OutQty*previous(StockRate)) is subtracted from CumulativeStockVal.

RowNum   TransType InQty   OutQty  Balance  CumulatveStockVal  StockRate

  1        IN      20       0       20      400                20
  2        IN      50       0       70      2400               34.285
  3        OUT     0        10      60      2057.15            34.285
  4        IN      10       0       70      2357.15            33.673

Please reply.Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using Window Offset Functions combining with AGGREGATE functions.

EDIT: I found you a tut where it is shown very clearly, watch from minute 15.

https://www.microsoftvirtualacademy.com/en-US/training-courses/querying-microsoft-sql-server-2012-databases-jump-start-8241?l=OZmttuJy_2304984382


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...