简体   繁体   English

MySQL不同的总和,按

[英]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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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