简体   繁体   中英

Mysql distinct sum, group by

This is my table:

id  user_id   type   value

1   1         type1     2
2   2         type1     1
3   1         type2     5
4   1         type1     2

I want output like this:

  user_id   type1   type2
    1         4     5
    2         1     0

please help

You can try like this:

SELECT 
    user_id, 
    sum( if( type = 'type1', value, 0 ) ) AS type1,  
    sum( if( type = 'type2', value, 0 ) ) AS type2
FROM 
    table_name 
GROUP BY 
    user_id;

I think, this is what you are searching for:

select 
   user_id,
   (select sum(value) from <yourtablename> sub1 where type = 'type1' where sub1.user_id = baseTable.user_id) as type1,
   (select sum(value) from <yourtablename> sub2 where type = 'type2' where sub2.user_id = baseTable.user_id) as type2,
from
   <yourtablename> baseTable

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