MySQL分组转置(分组列转行)
19 May 2018近期在做光大POC项目的时候,遇到了分组转置的问题,场景需求是将每个文件名对应的多行合并到一行,具体形式如下:
上述表格转化为:
想要达到分组转置的效果,需要使用group_concat()函数,具体语句如下:
select filename,
group_concat(topic) as trans_topic
from transposition group by filename;
-- 注意:必须使用group by分组
transposition数据表创建及导入代码:
-- 创建数据表
create table transposition(
filename varchar(100),
topic varchar(100)
);
-- 往表中插入数据
insert into transposition values("0849053.txt","临时调额-操作-卡片");
insert into transposition values("0849053.txt","卡片-状态-正常");
insert into transposition values("0849053.txt","卡片-属性-固定额度");
insert into transposition values("0849053.txt","卡片-包含-分期");
insert into transposition values("0849053.txt","卡片-包含-分期");
insert into transposition values("0907432.txt","还款金额-依赖-账单");
insert into transposition values("0907432.txt","账单-条件-正常还款");
insert into transposition values("0907432.txt","账单-条件-全额还款");
insert into transposition values("0907432.txt","账单-条件-全额还款");
insert into transposition values("0907432.txt","账单-依赖-还款");
insert into transposition values("0907432.txt","核实-操作-信息");
insert into transposition values("0907432.txt","卡片-属性-账单分期");
insert into transposition values("0909268.txt","调整-操作-额度");
insert into transposition values("0909268.txt","释放-操作-额度");
insert into transposition values("0909268.txt","额度-依赖-还款");
insert into transposition values("0909268.txt","核实-操作-身份");
insert into transposition values("0909268.txt","账单-依赖-还款");
insert into transposition values("0909268.txt","账单-依赖-还款");
分类: 数据库技术