Search code examples
mysqlsqlmysql-error-1064

MySql Error::error in sql syntax


MySql query below:

SELECT Name, 
SUM(Balance) AS Balance, 
(IF (Balance<=0), abs(Balance), 0 ) AS Exc, 
(IF (Balance>=0), Balance, 0 ) AS Del  
from table1 group by name

Mysql error:

You have an error in your sql syntax; check manual that corresponds to your MySql server version for the right syntax to use near

Solution

  • You can use CASE ... WHEN conditinnal statement like this

        SELECT Name, 
        SUM(Balance) AS Balance,
        (CASE WHEN SUM(Balance)>=0 THEN SUM(Balance) WHEN SUM(Balance)<0 THEN SUM(Balance) * -1 END) AS Balance_Positive
        from table1 group by name