您的位置:首页 > 数据库 > MySQL

Mysql group by 中行转列

2015-10-22 09:33 260 查看
我们在进行group by 的时候,有些列,我们不想进行聚合,比如上表的p,当我对match_id,expert_id,进行group by时,我想把p的值转成列类似于这样

也就是行转列,这时用到case when,语句如下

select match_id,expert_id,

sum(case parent_id WHEN 1 then p end) p1,

sum(case parent_id WHEN 2 then p end) p2,

sum(case parent_id WHEN 3 then p end) p3,

sum(case parent_id WHEN 4 then p end) p4,

sum(case parent_id WHEN 5 then p ELSE 0 end) p5,

sum(case parent_id WHEN 6 then p ELSE 0 end) p6,

sum(case WHEN parent_id is null then p ELSE 0 end) p7

from Table group by match_id,expert_id;

这句话表示对expert_id,match_id进行group by ,用case when 对p进行分类处理,通过parent_id 对p进行分类后,再用聚合函数,确保值唯一性,也可以使用其他聚合函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: