snippetsqlMinor
How to subtract the sum of columns from different tables?
Viewed 0 times
tablesthehowcolumnssubtractdifferentsumfrom
Problem
I have two tables:
I want to calculate a balance per
I could have two queries:
which gives me the total prize per account, and:
which gives me all withdrawals for these accounts.
Now, I'd like to subtract them to return balances for my accounts. What is the most efficient way to create a view like that?
- Withdrawals:
account_id+amount
- Prizes:
account_id+amount
I want to calculate a balance per
account, probably in a VIEW.I could have two queries:
SELECT account_id, SUM(amount) FROM prizes GROUP BY account_idwhich gives me the total prize per account, and:
SELECT account_id, SUM(amount) FROM withdrawals GROUP BY account_idwhich gives me all withdrawals for these accounts.
Now, I'd like to subtract them to return balances for my accounts. What is the most efficient way to create a view like that?
Solution
As an alternative to a full join, you could use
I am not sure how this query would compare to the full join solution but it looks simple enough to me to qualify as a good starting point.
UNION ALL to combine the two aggregated sets together, only the withdrawals set would be included with the negated results. You would then use the combined set as a derived table and aggregate the amounts per account_id once more:SELECT
account_id,
SUM(amount) AS balance
FROM
(
SELECT
account_id,
SUM(amount) AS amount
FROM
prizes
GROUP BY
account_id
UNION ALL
SELECT
account_id,
-SUM(amount) AS amount
FROM
withdrawals
GROUP BY
account_id
) AS derived
GROUP BY
account_id
;I am not sure how this query would compare to the full join solution but it looks simple enough to me to qualify as a good starting point.
Code Snippets
SELECT
account_id,
SUM(amount) AS balance
FROM
(
SELECT
account_id,
SUM(amount) AS amount
FROM
prizes
GROUP BY
account_id
UNION ALL
SELECT
account_id,
-SUM(amount) AS amount
FROM
withdrawals
GROUP BY
account_id
) AS derived
GROUP BY
account_id
;Context
StackExchange Database Administrators Q#212977, answer score: 5
Revisions (0)
No revisions yet.