This is a general SQL question, but I if you must know the database is Firebird.
I have this table (simplified):
user amount type -------------------- john 25 credit john 20 debit john 5 debit john 15 credit mike 15 credit
I want to have a result that looks like this, using a single query:
user credit debit -------------------- john 40 25 mike 15 NULL
Where credit = SUM(amount) WHERE type=credit
and debit = SUM(amount) WHERE type=debit
Basically I want to have multiple fields on the result based on a SUM of a field (in this case amount) but on different conditions (in this case type).
Thanks in advance for any suggestions.
Standard SQL would be:
SELECT "user",
SUM(CASE WHEN type='credit' then amount END) as Credit,
SUM(CASE WHEN type='debit' then amount END) as Debit
FROM
"table"
GROUP BY
"user"
I'm not sure how Firebird does it, but can you do something like:
SELECT user,
sum(SELECT amount FROM table AS t2 WHERE t2.user = t1.user AND type="credit" ) AS credit,
sum(SELECT amount FROM table AS t3 WHERE t3.user = t1.user AND type="debit" ) AS debit
FROM table AS t1
GROUP BY user
ORDER BY user
I'm referencing what I think it would be in PostgreSQL, in case that helps you find what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With