Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - where condition for each column

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.

like image 837
Valentin Despa Avatar asked Mar 20 '26 05:03

Valentin Despa


2 Answers

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"
like image 165
Damien_The_Unbeliever Avatar answered Mar 21 '26 20:03

Damien_The_Unbeliever


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.

like image 28
Bryce Siedschlaw Avatar answered Mar 21 '26 21:03

Bryce Siedschlaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!