I have a transaction table like above picture. Now I want to generate a summary report as follows:
What will be the best approach to write the SQL?
Please help. Thanks in advance :)
Another way to get the same result, but without extra grouping:
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
Check SQLFiddle
and one more option - without using 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
Check SQLFiddle
There are many approaches for achieveing the report. I have used Common table expression. You can modify the query and use joins aswell.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.