rwms
rwms

Reputation: 313

MySQL sum one column based on another

I have a fairly standard query that returns this table:

x  12  
y  59  
x  76  
x  35  
y  82  

I want to sum all 'x' values and all 'y' values separately. The result should be this:

x  123  
y  141  

I don't want to do this programmaticaly, if it can be done in MySQL. How do I go about doing this? Here's my sql query for reference:

SELECT
    tb1.val1,
    tb2.val2
FROM
    tb1 INNER JOIN tb2
ON
    tb1.id = tb2.id
WHERE
    (bunch of conditions unrelated to val1 and val2)
;

Upvotes: 1

Views: 835

Answers (1)

Pரதீப்
Pரதீப்

Reputation: 93694

You are looking for Group by and SUM aggregate

select tb1.val1, sum(tb2.val2)
From tb1 INNER JOIN tb2
.....
Group by tb1.val1

Upvotes: 7

Related Questions