墨痕淡去 2022-02-24 15:15 采纳率: 50%
浏览 65
已结题

sqlserver数据库查询问题

在对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
上面是从源数据库查询到的结果,怎么可以转换成我想要的目标形式的数据呢

  • 写回答

4条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2022-02-24 16:09
    关注
    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
    

    img


    上面这个sql已经考虑到数据里存在分组的情况了,sql不用改

    img

    话说你自己就没去试一下么?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 3月12日
  • 已采纳回答 3月4日
  • 修改了问题 2月24日
  • 修改了问题 2月24日
  • 展开全部

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改