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进行分类后,再用聚合函数,确保值唯一性,也可以使用其他聚合函数
也就是行转列,这时用到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进行分类后,再用聚合函数,确保值唯一性,也可以使用其他聚合函数
相关文章推荐
- mysql数据库备份与恢复命令
- mysql数据库备份与恢复命令
- 重新设置MySQL的root密码
- 【Navicat for MySQL】提示2003 - can't connect to MySQL server on 'localhost' 10060
- MySQL系列二
- mysql集群之keepalived简单搭建
- [实战]MVC5+EF6+MySql企业网盘实战(6)——ajax方式登录
- mysql 不能插入中文和显示中文
- mysql sql优化实例1(force index使用)
- ubuntu下安装mysql
- from_unixtime mysql 日期时间格式化
- MYSQL 时间函数总结
- mysql GROUP BY 分组
- [每日一答] [20151017] MySQL 使用 MRG_MyISAM 存储引擎来实现分表
- mysql基础
- Mysql中使用索引的典型场景
- mysql管理
- MySQL数据类型
- MySQL 数据库信息
- win下安装mysql 遇到的问题