Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two column in Sql Table
and want result in third column Like This
in This Column When Bill Is entered it will add in Balance and show in third column same as when Payment Paid it will Less from Balance

		Bill	  Paid	     Balance	
1		75	      0	        75	
2		0	      50	    25	
3		780	      0	        805	
4		500	      0	        1305	
5		0	      1000	    305	
6		780	      0	        1085	
7		77	      0 	    1162	


What I have tried:

SELECT  [Bill] ,[Paid] ,[Bill]-Paid  as Balance  FROM [CsLedg]


and showing which is not Ok for me

<pre>
		Bill	  Paid	     Balance	
1		75	      0	        75	
2		0	      50	    -50	
3		780	      0	        780	
4		500	      0	        500	
5		0	      1000	    -1000
6		780	      0	        780	
7		77	      0 	    77	
Posted
Updated 20-Dec-20 21:24pm
v3

You need a running balance, which means either a self join, or using LAG (Transact-SQL) - SQL Server | Microsoft Docs[^]
 
Share this answer
 
Take a look here: Calculating Running Total with OVER clause and Partition By Clause in SQL Server[^]

So, in your case it should be like this:
SQL
CREATE TABLE CsLedg
(
  LedgId int IDENTITY(1,1),
  Bill int,
  Paid int
);

INSERT INTO CsLedg(Bill, Paid)
VALUES(75, 0),
(0, 50),
(780, 0),
(500, 0),
(0, 1000),	
(780, 0),
(77, 0);

SELECT LedgId, Bill, Paid, SUM(Bill-Paid) OVER(ORDER BY LedgId) As Balance
FROM CsLedg


SQL Server 2019 | db<>fiddle[^]


More examples:
Use SQL to Calculate a Running Total - Essential SQL[^]
4 Ways to Calculate a Running Total With SQL[^]
 
Share this answer
 
v2

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