Harzio
Harzio

Reputation: 75

SQL Server - How to calculate Stock from In and Out column

I have table in SQL Server to track Date, Quantity In, & Quantity Out. I want to calculate current Stock column.

Date        InQty      OutQty      Stock
1 Sep 2018  1000        200        800
2 Sep 2018  0           300        500
3 Sep 2018  1000        100        1400

I want to create SQL Server Query to calculate the Stock value as shown above. I am really appreciate for any help..

Upvotes: 1

Views: 1293

Answers (1)

gotqn
gotqn

Reputation: 43626

Try this:

DECLARE @DataSource TABLE
(   
    [Date] DATE
   ,[InQty] INT
   ,[OutQty] INT
);

INSERT INTO @DataSource ([Date], [InQty], [OutQty])
VALUES ('20180901', 1000, 200)
      ,('20180902', 0, 300)
      ,('20180903', 1000, 100);

SELECT *
      ,SUM([InQty]-[OutQty]) OVER (ORDER BY [Date])
FROM @DataSource
ORDER BY [Date];

enter image description here

Upvotes: 2

Related Questions