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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With