For each user, I want to produce an aggregate result. However, I keep running into the problem of the subquery returning more than 1 result.
SELECT **[user]**,
((SELECT SUM(amount)
FROM transactions
WHERE [user] = **[user]**
AND [type] = 'credit' ) -
(SELECT SUM(amount)
FROM transactions
WHERE [user] = **[user]**
AND [type] = 'debit' ))
FROM transactions
How do I get the user from the select at the start to then operate as the variable user in the subqueries?
use
CASEto simplify the summing:If credit and debit are the only valid types, then it can be simplified further as:
The answers using subqueries for the summing activity, whilst still selecting user from the transactions table will perform the summation multiple times – once for every row in the transactions table – so if one user has 5 transactions, they’re going to compute the sums 5 times (and show 5 result rows), which I assume you do not want.