用于生成财务事务摘要报告的SQL

时间:2014-11-05 05:49:36

标签: sql oracle transactions

Transaction Table

我有一张如上图所示的交易表。现在我想生成一个摘要报告如下:

Result Table

编写SQL的最佳方法是什么?

请帮忙。在此先感谢:)

2 个答案:

答案 0 :(得分:2)

获得相同结果的另一种方法,但没有额外的分组:

WITH base AS
(
  SELECT Debtor_Acc As Account_NO, Amount*-1 as Amount FROM transaction
  UNION ALL
  SELECT Creditor_Acc, Amount FROM transaction
)
SELECT Account_NO, SUM(Amount) Amount
FROM base
GROUP BY Account_NO

检查SQLFiddle


还有一个选项 - 不使用CTE:

SELECT Account_NO, SUM(Amount) Amount
FROM
(
  SELECT Debtor_Acc As Account_NO, Amount*-1 as Amount FROM transaction
  UNION ALL
  SELECT Creditor_Acc, Amount FROM transaction
)
GROUP BY Account_NO

检查SQLFiddle

答案 1 :(得分:1)

实现该报告的方法有很多种。我使用了Common表表达式。 您也可以修改查询并使用连接。

WITH CTE (Account_NO,Amount)
AS
(
SELECT Debtor_Acc As Account_NO,-SUM(Amount) Amount 
FROM transaction GROUP BY Debtor_Acc
UNION
SELECT Creditor_Acc,SUM(Amount) 
FROM transaction GROUP BY Creditor_Acc
)
SELECT Account_NO,SUM(Amount) FROM CTE 
GROUP BY Account_NO