1

I have 3 columns in my MySQL table type, sum and custom_sum where custom_sum can be empty, and i am stuck on modifying query

SELECT `type`, SUM(`sum`) FROM `localhost-test` GROUP BY `type`

What i need is to use sum in SUM() if custom_sum is empty, and use custom_sum if it is not. Is it possible to sum by different columns based on "if" statement in mysql ?

2
  • SUM(ISNULL(custom_sum, `sum`)) Commented Apr 22, 2014 at 8:06
  • 1
    What exactly you mean by saying "empty"? If it's NULL value, then use COALESCE as @Notolysses told below in his answer. If empty means 0 or "", then you need to use IF or CASE. Just don't do as user3414693 said, but enclose IF or CASE inside SUM(...). Commented Apr 22, 2014 at 8:12

1 Answer 1

3

If custom_sum value is null :

SELECT 
    `u.type`,
    SUM(COALESCE(`custom_sum`,`sum`))
FROM 
    `localhost-test` 
GROUP BY 
    `type`

If custom_sum value is empty (=='') :

 SELECT 
    `u.type`,
    SUM(CASE WHEN `custom_sum` = '' THEN `sum` ELSE `custom_sum` END)
FROM 
    `localhost-test` 
GROUP BY 
    `type`
Sign up to request clarification or add additional context in comments.

2 Comments

can use coalesce for empty string like NULL??
@Ronald Alexander Kailola : Thank you for a tip, I've updated my answer in case value is empty but not null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.