tags:

views:

71

answers:

3

I have one table named LedgerReport which contain customer name,sales bill number and amount and i have to generate the balance of customer wise one by one row without using the cursors

and i hav send u the sample report below so please send me some suggestion to solve my problem...

Create Table LedgerReport 
(
    Customer Nvarchar(64),
    Billno Nvarchar(64),
    Amount Decimal (10,3)
)

Insert Into LedgerReport Values ('Prem','Sb-001','5000')
Insert Into LedgerReport Values ('Prem','Sb-002','7000')
Insert Into LedgerReport Values ('Prem','Sb-003','2000')
Insert Into LedgerReport Values ('Prem','Sb-004','8000')
Insert Into LedgerReport Values ('Biswo','Sb-005','2000')
Insert Into LedgerReport Values ('Biswo','Sb-006','3000')
Insert Into LedgerReport Values ('Biswo','Sb-007','4000')
Insert Into LedgerReport Values ('Biswo','Sb-008','5000')

 

Select * from LedgerReport
------------------------------------------------
Customer  BillNo     Amount    **Balance**  
----------------------------------------------
Prem      Sb-001   5000.000   **5000.000**
Prem      Sb-002   7000.000  **12000.000**
Prem      Sb-003   2000.000  **14000.000**
Prem      Sb-004   8000.000  **22000.000**
Biswo     Sb-005   2000.000   **2000.000** 
Biswo     Sb-006   3000.000   **5000.000**
Biswo     Sb-007   4000.000   **9000.000**
Biswo     Sb-008   5000.000  **14000.000**
+2  A: 
SELECT Customer, BillNo, Amount
    ,(SELECT SUM(Amount) 
                FROM LedgerReport 
               WHERE Customer = L.Customer
                 AND BillNo <= L.BillNo)
      'Running Total'
FROM LedgerReport L
Dave Barker
Bill number is not an integer or number, so probably the '<=' wouldnt work.
Richie
It does seem like an generated sequence.
astander
The '<=' does work on string comparisons.
Dave Barker
A: 

SELECT Customer,SUM(Amount)
FROM LedgerReport
GROUP BY Customer

User1
Biswo needs each row with balance updated.
Richie
+1  A: 

You can also try this to avoid selects in the column list

SELECT  l.Customer,
     l.Billno,
     l.Amount,
     SUM(lBal.Amount) RunningTotal
FROM    LedgerReport L LEFT JOIN
     LedgerReport lBal ON L.Customer = lBal.Customer
          AND L.Billno >= lBal.Billno
GROUP BY l.Customer,
     l.Billno,
     l.Amount
astander