Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Sum positive and negative - calculate the exact total from money transactions

Tags:

sql

mysql

I have a database table full of transactions. The transactions contain negative numbers from people returning items. I would like to add up all the amount field while also subtracting the negative values of returns from the total. How can I do this and output it out? Currently the best I can do is get:

  SELECT SUM(amount) 
  FROM outputaddition 
  GROUP by SIGN(amount);

But this only puts positive and negative in the same column.

like image 433
Kravitz Avatar asked Apr 07 '14 10:04

Kravitz


People also ask

How do you sum positive and negative numbers in SQL?

You can use sign to separate the values: select Sum( ( Sign( n ) + 1 ) / 2 * n ) as PositiveSum, Sum( -( Sign( n ) - 1 ) / 2 * n ) as NegativeSum from YourTableOData; Sign returns 1 , 0 or -1 depending on the sign of the input value.

How do I find the total of a column in MySQL?

SELECT count(*) AS anyName FROM information_schema. columns WHERE table_name =' yourTableName'; Applying the above syntax in the example table with the name 'NumberOfColumns'. mysql> SELECT count(*) AS NUMBEROFCOLUMNS FROM information_schema.


1 Answers

SELECT personId,SUM(CASE WHEN amount<0 THEN amount ELSE 0 END) as NegativeTotal,
       SUM(CASE WHEN amount>=0 THEN amount ELSE 0 END) as PostiveTotal
FROM outputaddition
GROUP BY personID

If you want single column

SELECT personId,SUM(amount) as Total
FROM outputaddition
GROUP BY personID
like image 183
Mudassir Hasan Avatar answered Oct 18 '22 10:10

Mudassir Hasan