开发者

SQL Query to generate balance

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')

&nbs开发者_如何学运维p;

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**


SELECT Customer, BillNo, Amount
    ,(SELECT SUM(Amount) 
                FROM LedgerReport 
               WHERE Customer = L.Customer
                 AND BillNo <= L.BillNo)
      'Running Total'
FROM LedgerReport L


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜