在对sqlserver数据库进行查询,同一个ID下有多条数据,但是只有一个字段的内容是不一样的,其他字段的内容都完全相同,怎么才可以将多条数据整合成一条数据呢?
举例:
对1001这个ID,查询数据有3条:
id name sex age text
1001 tom 1 12 a
1001 tom 1 12 b
1001 tom 1 12 c
想要得到的结果:
id name sex age text
1001 tom 1 12 a,b,c
请问这种应该怎么实现呢
上面举例有问题,单一一条例子不具有原数据的代表性,原数据有很多,只举几条例子,重新修改一下例子:
《源数据库》
id name sex age text
1001 tom 1 12 a
1001 tom 1 12 b
1001 tom 1 12 c
1002 lucy 2 14 z
1002 lucy 2 14 y
1003 tony 1 13 x
1004 peter 2 13 d
1004 peter 2 13 e
1004 peter 2 13 f
1004 peter 2 13 g
应该得到的结果:
《目标形式》
id name sex age text
1001 tom 1 12 a,b,c
1002 lucy 2 14 z,y
1003 tony 1 13 a
1004 peter 2 13 d,e,f,g
上面是从源数据库查询到的结果,怎么可以转换成我想要的目标形式的数据呢
with t as (
select 1001 id, 'tom' name, 1 sex, 12 age, 'a' text union all
select 1001, 'tom' ,1 ,12, 'b' union all
select 1001 ,'tom' ,1 ,12 ,'c')
select t.id,t.name,t.sex,t.age,
stuff((select ','+t2.text from t as t2 where t2.id=t.id and t2.name=t.name and t2.sex=t.sex and t2.age=t.age for xml path('')),1,1,'') text
from t group by t.id,t.name,t.sex,t.age
上面这个sql已经考虑到数据里存在分组的情况了,sql不用改
话说你自己就没去试一下么?
select id,name,sex,age,max(text) from table1 group by id,name,sex,age
group_concat函数,默认逗号分隔
select id,name,sex,age, group_concat(text) from table group by id,name,sex,age
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!