SQL Query生成平衡

时间:2009-11-18 04:40:06

标签: sql-server

我有一个名为LedgerReport的表,其中包含客户名称,销售单号和金额,我必须逐行生成客户明智的余额,而不使用游标

我发送下面的样本报告,所以请给我一些建议来解决我的问题...

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您也可以尝试此操作以避免列列表中的选择

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

答案 2 :(得分:0)

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