Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql - can I select values from the same column and show them in 2 columns result?

Tags:

sql

mysql

suppose I have a table of an account entries moves, Like

ACCOUNTS table
+-------+------+---------+
| title | side | balance |
+-------+------+---------+
| cash  | debit|  500.0  |
+-------+------+---------+
| cash  |credit|  300.0  |
+-------+------+---------+
| cash  |credit|  600.0  |
+-------+------+---------+
#..... more than 10'000 debit and credit rows

I want to group the sum of credit rows and the sum of debit rows and show every sum of them in different column.

what I tried to do is to sum the balance on groups of sides , like

select title, side, sum(balance) from accounts group by side

I get 2 rows , one for debits sum, and another for credit sum, like

+-------+------+---------+
| cash  | debit|  500.0  |
+-------+------+---------+
| cash  |credit|  900.0  |
+-------+------+---------+



What I want is to get the whole result in ONE result row, the sum of debits in one field and the sum of credits in another field. I want the end result to be something like this
+-------+-------+-------+
| cash  | 500.0 | 900.0 |
+-------+-------+-------+

Thanks.

like image 303
Accountant م Avatar asked Jan 24 '26 06:01

Accountant م


2 Answers

You can use case

select title, sum( case side when 'debit' then balance else 0 end ), 
   sum( case side when 'credit' then balance else 0 end )
from accounts 
group by title
like image 192
ScaisEdge Avatar answered Jan 26 '26 20:01

ScaisEdge


Here's an example using subqueries. A lot more verbose than the CASE statement already provided but if you end up having more than one title or want to do calculations it makes it pretty straightforward.

SELECT
    title
    ,credit.credit_balance
    ,debit.debit_balance
    ,(credit.credit_balance - debit.debit_balance) AS net
FROM 
    (SELECT
        title,
        sum(balance) debit_balance
    FROM accounts
    WHERE 
        side = 'debit'
    GROUP BY side) debit
INNER JOIN (
    SELECT
        title,
        sum(balance) debit_balance
    FROM accounts
    WHERE
        side = 'credit'
    GROUP BY side) credit ON debit.title = credit.title
GROUP BY
    title;
like image 27
matthew. Avatar answered Jan 26 '26 19:01

matthew.



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!