我需要您帮助我从一个表中提取金融交易及其行的查询,如下所示: 帐号:例如(4568643) Transactionamount:例如(1000美元) Kindoftransaction(借记或贷记) transactionfile(此编号包含链接到此事务的文件编号)
我需要你的帮助来在总和之后提取每个(事务文件)的净余额的查询 (Transactionamount)持有(Kindoftransaction)的“信用”并从All(Transactionamount)的总和减去它“借记”所在的地方 (帐号)是(4568643)
答案 0 :(得分:0)
这有帮助吗? - 请注意,如果您可以发布表格定义
,这会有所帮助DECLARE @transactions TABLE
(
[AccountNumber] INT NOT NULL,
[TransactionAmount] DECIMAL(18, 10) NOT NULL,
[KindOfTransaction] CHAR(1) NOT NULL, -- this could be better served as a boolean / bit field
[TransactionFile] INT NOT NULL
)
-- dummy data
INSERT INTO @transactions VALUES(4568643, 100, 'C', 123)
INSERT INTO @transactions VALUES(4568643, 150, 'C', 124)
INSERT INTO @transactions VALUES(4568643, 50, 'D', 125)
INSERT INTO @transactions VALUES(2345623, 100, 'C', 126)
INSERT INTO @transactions VALUES(2345623, 79, 'C', 127)
-- here's the actual query to return your data using a common table expression
;WITH cteAccountSummary (AccountNumber, TotalCredits, TotalDebits) AS (
SELECT [AccountNumber],
SUM(
CASE [KindOfTransaction]
WHEN 'C' THEN [TransactionAmount]
ELSE 0
END
),
SUM(
CASE [KindOfTransaction]
WHEN 'D' THEN [TransactionAmount]
ELSE 0
END
)
FROM @transactions
GROUP BY [AccountNumber]
)
SELECT [AccountNumber], TotalCredits - TotalDebits AS 'NetFinancialPosition'
FROM cteAccountSummary
答案 1 :(得分:0)
select transactionfile, sum(case when kindoftransaction = 'debit' then -1 else 1 end * transactionamount)
from financial
where accountnumber = 4568643
group by transactionfile