SQL - where condition for each column
-
09-09-2020 - |
Question
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.
Solution
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"
OTHER TIPS
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.
try this :
SELECT credit.user_name, credit.cre, debit.deb
FROM (SELECT user_name, SUM(amount) cre FROM t WHERE TYPE = 'credit' GROUP BY user_name) credit
LEFT OUTER JOIN (SELECT user_name, SUM(amount) deb
FROM t
WHERE TYPE = 'debit'
GROUP BY user_name) debit
ON (credit.user_name = debit.user_name)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow