Answer the question
In order to leave comments, you need to log in
How to subtract the sum of some values from others in one table according to different characteristics in a column?
Good afternoon. I don’t know how to ask the question correctly, but it’s better to try to tell what is:
Suppose there is a table:
CREATE TABLE IF NOT EXISTS tablename(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`type` int(11) NOT NULL,
`sum` varchar(50) NOT NULL default '0',
PRIMARY KEY ( `id` )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Answer the question
In order to leave comments, you need to log in
Here is a possible solution:
select
sum(if(`type` = 0, `sum`, 0)) `income`,
sum(if(`type` = 1, `sum`, 0)) `outcome`,
sum(if(`type` = 0, `sum`, -`sum`)) `balance`
from tablename;
it is possible sum aggregate function can work also on expressions.
https://metanit.com/sql/mysql/6.4.php
classic case is in all dialects of SQL
if - a simplified version in Muska and a number of others
It turns out that we need to calculate for rows that match the conditions the sum of the expression
amount for the operation will be multiplied by 1 or - one.
ps It
is better not to name the field in the database with the names of keywords or functions,
otherwise you will have to quote all the times. I'm talking about the field name sum
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question