Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the sum which is greater than 0 or less than 0 using MySQL

Tags:

database

mysql

I have a MySQL query that will get the sum of the amount in my column. What I found out is that there are also negative values in my data. I want to separate the sum of positive values and negative values. Can you help me on this?

I tried this query... but its giving me a Invalid use of group function.

Here's my query:

SELECT sum(AMOUNT) from deposit where type = 42 and sum(AMOUNT) > 0 
like image 799
Rukikun Avatar asked Oct 13 '25 09:10

Rukikun


2 Answers

I found the solution which was posted by someone earlier but unfortunately he deleted it(i dont know why) Thanks to that person. :)

I tried to consider the Having clause but its giving me a wrong result.

SELECT sum(CASE WHEN AMOUNT > 0 THEN AMOUNT ELSE 0 END) as Positive, 
sum(CASE WHEN AMOUNT < 0 THEN AMOUNT ELSE 0 END) as Negative from deposit where type = 42
like image 165
Rukikun Avatar answered Oct 15 '25 00:10

Rukikun


Use having

SELECT sum(AMOUNT) from deposit where type = 42 and amount > 0 having sum(AMOUNT) > 0 
like image 30
praneet drolia Avatar answered Oct 14 '25 23:10

praneet drolia