简体   繁体   中英

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)
;

You are looking for Group by and SUM aggregate

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM