总和基于cndition的借方和贷方的运行价值

时间:2015-08-27 14:37:14

标签: sql sql-server

我有这个查询来运行带有运行值的值信用

USE tempdb
GO
DROP TABLE TestTable
CREATE TABLE TestTable (ID INT, CREDIT INT,DEBIT INT, TXT NVARCHAR(MAX))
INSERT INTO TestTable (ID, CREDIT,DEBIT,TXT)
SELECT 1, 10,-20,'A' UNION ALL
SELECT 2, 20,-30,'B' UNION ALL
SELECT 3, 30,0,'C' UNION ALL
SELECT 4, 40,0,'C' UNION ALL
SELECT 5, 50,-30,'B' UNION ALL
SELECT 6, 60,0,'A' UNION ALL
SELECT 7, 70,0,'A'
GO


  SELECT ID,txt, CREDIT,DEBIT
,SUM(CREDIT)  OVER(ORDER BY ID ROWS UNBOUNDED PRECEDING)   AS RunningTotal
FROM TestTable AS T

我需要此查询根据带有借方或贷方的条件求和

if txt = 'A' then Running value + credit
if txt = 'B' then Running value + debit

感谢

2 个答案:

答案 0 :(得分:1)

这适用于Oracle:

SELECT SUM(CASE WHEN txt = 'A' THEN CREDIT WHEN txt = 'B' THEN DEBIT END)
FROM TestTable

答案 1 :(得分:1)

您可能只想要sum()中的条件:

SELECT ID, txt, CREDIT, DEBIT,
       SUM(CASE WHEN txt = 'A' THEN CREDIT
                WHEN txt = 'B' THEN DEBIT
                ELSE 0
            END)  OVER (ORDER BY ID) AS RunningTotal
FROM TestTable T;

对于累积总和,不需要(unbounded preceding)。如果else 0既不是txt也不是A,则B将处理初始案例。我想你会想要0