SQL 如何将一个表中的两条或多条拥有相同ID的记录合并为一条?

 我来答
幸运的小李菲刀
2018-01-09 · TA获得超过1.7万个赞
知道小有建树答主
回答量:38
采纳率:90%
帮助的人:1.8万
展开全部

一、创建表:

  • create table stuUnion

    (

    sid int identity primary key,

    cid int,

    id varchar(500)

    )

二、添加数据:

  • insert into stuUnion

    elect 1,'a' union

    select 1,'b' union

    select 2,'c' union

    select 2,'d' union

    select 3,'e' union

    select 3,'f' union

    select 3,'g'

三、用标量函数查询:

  1. 创建标量函数:

    create function b(@cid int)

    returns varchar(500)

    as

    begin

    declare @s varchar(500)

    select @s=isnull(@s+'','')+rtrim(id)+',' from stuUnion where cid=@cid

    return @s

    end;

  2. 用标量函数查询:

    select cid,dbo.b(cid) as id from stuUnion group by cid

  3. 用sqlserver的xml:

    select cid,ID=STUFF((select ' '+rtrim(id)+',' from stuUnion where st.cid=cid order by id for XML path('')),1,1,'') from stuUnion st group by cid

本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式