1

我有一个情况。

我有包含像这样的贷方和借方列的数据表

Month     Credit     Debit
Sep       1422825      0
Oct         0        1422825
Oct       1695017.5    0
Nov         0         1400000
Nov         0         295018

我想要一个应该像这样显示的余额

Month     Credit     Debit       Balance
Sep       1422825      0
Oct         0        1422825      (1422825 of Credit-1422825 of Debit)=0
Oct       1695017.5    0
Nov         0         1400000     
Nov         0         295018       (1695017.5 of credit-1400000+295018)=0.5

它应该显示在水晶报告上怎么做。

4

1 回答 1

0

这是您针对 2005 年优化的解决方案,我相信它在 2008 年运行良好。(使用整数表示月份,它更容易......)

DECLARE @Temp TABLE (Month int, Credit money, Debit money, Balance money)

DECLARE @RunningTotal money

SET @RunningTotal = 0

INSERT INTO @Temp
SELECT Month, Credit, Debit, null
FROM Datatable
ORDER BY Month

UPDATE @Temp
SET @RunningTotal = Balance = @RunningTotal + Credit - Debit
FROM @Temp

SELECT * FROM @Temp

编辑(从第一步开始):

如果您需要仅显示组(月)中的最后一条记录,则可以使用排名功能,例如...

;WITH Temp2 AS
(
    SELECT 
        *,
        ROW_NUMBER() OVER (
            PARTITION BY Month
            ORDER BY Credit DESC, Debit DESC -- whatever order inside group you need
        ) AS N
     FROM @Temp
)
SELECT
    Month,
    Credit, 
    Debit, 
    Balance = CASE WHEN N = 1 THEN Balance ELSE NULL END
FROM Temp2

这未经测试,直接从我的脑海中编写的代码:P

于 2013-06-14T11:30:44.573 回答