Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I have this structure in my table
id|source_id|val1|val2 1 |1 |10 |NULL 2 |1 |NULL|3 3 |2 |NULL|5 4 |2 |4 |NULL 5 |3 |7 |NULL
ANd i want to have this in mysql
source_id|total 1 |13 2 |9 3 |7
Can you help me please
Ifnull()
null
Sum()
Group By
Do the following:
SELECT ressource_id, SUM(IFNULL(val1, 0)) + SUM(IFNULL(val2, 0)) AS total FROM your_table GROUP BY ressource_id
Add a comment
I think you want:
select source_id, coalesce(sum(val1), 0) + coalesce(sum(val2), 0) from t group by source_id;
I would do the NULL conversion after the SUM(), because some source_ids only have NULLs in one of the columns.
NULL
SUM()
source_id
SELECT q.resource_id, ( q.val1 + q.val2 ) AS total FROM (SELECT resource_id, Ifnull(Sum(val1), 0) AS val1, Ifnull(Sum(val2), 0) AS val2 FROM `table` GROUP BY resource_id) AS q
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.