mysql 表行数据根据某个相同字段合并的的sql语句怎么写啊!
例如一张表:
原表
id | staff | record
1 | vip | 16:25:00
2 | ken | 16:25:10
3 | vip | 16:38:00
4 | ken | 16:38:00
5 | ken | 16:42:00
目标
id | staff | record1 | record2 | record3
1 | vip | 16:25:00 | 16:38:00 | null
2 | ken | 16:25:10 | 16:38:00 | 16:42:00
这是个例子,实际上原表很多行数据的,所以静态的写法就不用写了。
例如一张表:
原表
id | staff | record
1 | vip | 16:25:00
2 | ken | 16:25:10
3 | vip | 16:38:00
4 | ken | 16:38:00
5 | ken | 16:42:00
目标
id | staff | record1 | record2 | record3
1 | vip | 16:25:00 | 16:38:00 | null
2 | ken | 16:25:10 | 16:38:00 | 16:42:00
这是个例子,实际上原表很多行数据的,所以静态的写法就不用写了。
解决方案
10
目前只能实现这个,希望对你有点帮助~
select id,staff,group_concat(record separator “|”) from test group by staff;
select id,staff,group_concat(record separator “|”) from test group by staff;
10
1、按 staff分组,取最大COUNT(*)(bz)
2、打开游标循环取值,字符串累加生成SQL语句,如下述格式
sum(if(bz=1,…,….)),
sum(if(bz=2,…,….)),
….
再执行
2、打开游标循环取值,字符串累加生成SQL语句,如下述格式
sum(if(bz=1,…,….)),
sum(if(bz=2,…,….)),
….
再执行
30
sql语句:
select max(bz) into @nu from (
select staff,count(*) as bz from tt group by staff) a
sp循环
set i=1;
set @asql=””;
while i<=@nu do
set @asql=concat(“sum(if(bz=”,i,…) 本人写SQL语句
set i=i+1;
end while
生成标识字段:
set @q=1;
set @a=””;
select *,@q:=if(@a=staff,@q+1,1),@a=staff from tt
select max(bz) into @nu from (
select staff,count(*) as bz from tt group by staff) a
sp循环
set i=1;
set @asql=””;
while i<=@nu do
set @asql=concat(“sum(if(bz=”,i,…) 本人写SQL语句
set i=i+1;
end while
生成标识字段:
set @q=1;
set @a=””;
select *,@q:=if(@a=staff,@q+1,1),@a=staff from tt
10
select * from 原表 A ,目标 B where A.id=B.id