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 |
+-------+------+---------+
+-------+-------+-------+ | cash | 500.0 | 900.0 | +-------+-------+-------+
Thanks.
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
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.