Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more: , +
How to Decrements value column by previous row in select sql statement

for ex in tabl
name  qty     open qty
aaa  1200     1500
bbb   2000    5000
aaa    200


and sql query i want to add temp values .

name qty total
aaa  1200 300
bbb  2000 3000
aaa  200  100


this is openqty - previous qty
here total is temporary variable..
Posted
Updated 16-Mar-16 10:58am
v2
Comments
Savalia Manoj M 24-Jul-13 8:48am    
i can not understand your question. Please specify with proper example.

1 solution

Try this:

SQL
DECLARE @tmp TABLE([name] VARCHAR(30), [qty] INT, [open qty] INT NULL) 

INSERT INTO @tmp ([name], [qty], [open qty])
SELECT 'aaa',  1200, 1500
UNION ALL SELECT 'bbb', 2000, 5000
UNION ALL SELECT 'aaa', 200, 300

SELECT [name], [qty], [open qty], [open qty]- [qty]  AS [total]
FROM @tmp


Result:
name    qty     open q. total
aaa	1200	1500	300
bbb	2000	5000	3000
aaa	200	300	100
 
Share this answer
 
Comments
Herman<T>.Instance 24-Jul-13 10:38am    
CTE solution?
Maciej Los 24-Jul-13 11:19am    
No, it's not.
Herman<T>.Instance 26-Jul-13 4:40am    
If a CTE could be more handy in this case, that was the intended question.
Maciej Los 26-Jul-13 4:51am    
I don't think so that CTE is more handy in this case. It's simple subtraction...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900