2014-11-05 62 views
1

Transaction Table用于生成金融交易汇总报告的SQL

我有一个类似上图的交易表。现在,我要生成一个总结报告如下:

Result Table

会是怎样写的SQL的最佳方法?

请帮忙。在此先感谢:)

+1

这个问题似乎是无关紧要的,因为它是一个需求描述。 – 2014-11-05 05:51:49

+0

我可以使用公用表表达式来做到这一点。但我想知道是否有更好的方法。感谢您的投票:) – 2014-11-05 05:57:16

+0

这是一个**总结**(不是*总结*) – 2014-11-05 06:11:39

回答

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

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

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 
+0

你有代码中的错字 - 在底部查询 – 2014-11-05 06:57:41

+0

Thankx @Andrey :)。我纠正了这一点。 – 2014-11-05 08:56:08