Mysql group by 中行转列

来源:互联网 发布:mac设置iphone铃声2017 编辑:程序博客网 时间:2024/05/01 06:06

我们在进行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进行分类后,再用聚合函数,确保值唯一性,也可以使用其他聚合函数


1 0
原创粉丝点击