Reputation: 50173
I have table structure as below:
STOCKNO QTY OP
12345 1.00 +
12345 25.00 -
12345 1.00 -
12345 10.00 +
123456 10.00 +
123456 1.00 -
I want to get the actual qty balance of each stockno by +, -
+ (i.e. Purchase Qty)
- (i.e. Sales Qty)
But for above I am getting total purchase qty & sales qty using below query:
SELECT STOCKNO, SUM(QTY) as QTY, OP
FROM DT
GROUP BY STOCKNO, OP
AND I want to get the actual closing qty record of each stock.
Upvotes: 0
Views: 106
Reputation: 492
select STOCKNO,OP, sum(QTY) OVER(PARTITION BY STOCKNO,OP) as StockLevel
from DT
Upvotes: 0
Reputation: 81990
Another options (just for fun) is to concat() the OP and Qty
Example
Select STOCKNO
,Ttl = sum(convert(decimal(10,2),concat(OP,QTY)))
from YourTable
Group By STOCKNO
Returns
STOCKNO Ttl
12345 -15.00
123456 9.00
Upvotes: 0
Reputation: 11205
Use a case inside the sum
select STOCKNO, sum(case when OP = '+' then 1 else -1 end * QTY) as StockLevel
from DT
group by STOCKNO
Upvotes: 0
Reputation: 204884
SELECT STOCKNO,
SUM(case when OP = '-' then -QTY else QTY end) as BALANCE
FROM DT
GROUP BY STOCKNO
Upvotes: 2