Reputation: 3731
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 ?
Upvotes: 1
Views: 88
Reputation: 44581
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`
Upvotes: 3