我有一个情况。
我的数据表包含像这样的Credit和Debit列
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
它应该在水晶报告上显示如何做。
答案 0 :(得分: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