Debit and Credit with Running Balance

Analyst_SQL 3,551 Reputation points
2023-10-06T06:58:30.1766667+00:00

I want Ledger Report of Customer 1001 'Akhter' with below Data

Create table #Tbl_Customer (C_ID int,C_Name varchar(50))

Create table #tbl_Ledger (ID int,E_Date date,Debit_Head_ID int,Credit_Head_ID int,T_Amount Decimal(10,2) )


insert into #Tbl_Customer values (1001,'Akhter')
insert into #Tbl_Customer values (1002,'Noman')

Insert into #tbl_Ledger values (1,'2023-10-01',1001,1002,4000) 
Insert into #tbl_Ledger values (2,'2023-10-02',1001,1002,1000) 
Insert into #tbl_Ledger values (3,'2023-10-03',1002,1001,1000) 
Insert into #tbl_Ledger values (4,'2023-10-03',1002,1001,3000) 
Insert into #tbl_Ledger values (5,'2023-10-04',1002,1001,3000) 
Insert into #tbl_Ledger values (6,'2023-10-04',1001,1002,6000) 


Output

User's image

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,004 questions
SQL Server Reporting Services
SQL Server Reporting Services
A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.
2,845 questions
SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,479 questions
SQL Server Analysis Services
SQL Server Analysis Services
A Microsoft online analytical data engine used in decision support and business analytics, providing the analytical data for business reports and client applications such as Power BI, Excel, Reporting Services reports, and other data visualization tools.
1,253 questions
0 comments No comments
{count} votes

Accepted answer
  1. CosmogHong-MSFT 24,106 Reputation points Microsoft Vendor
    2023-10-06T07:14:43.91+00:00

    Hi @Analyst_SQL

    Try this query:

    ;WITH CTE AS
    (
    SELECT ID,E_Date
          ,CASE WHEN Debit_Head_ID=1001 THEN T_Amount ELSE 0 END AS Debit
    	  ,CASE WHEN Credit_Head_ID=1001 THEN T_Amount ELSE 0 END AS Credit
    FROM #tbl_Ledger
    )
    SELECT ID,E_Date,Debit,Credit,SUM(Debit-Credit)OVER(ORDER BY E_Date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)AS Balance
    FROM CTE
    

    Best regards,

    Cosmog Hong

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful