有一个sql语句如何写

fstao 2016-12-18 06:20:47
数据库是:sqlserver2005,数据如下:
表t1(id int,code varchar(200))


id code
1 A001
1 A002
2 A003
3 A004
3 A005



我想显示如下:

id code
1 A001,A002
2 A003
3 A004,A005



能否不要用循环语句来实现,因为当数据量大的时候会很慢,也不能用游标来实现。
请问这个sql语句如何实现?
...全文
143 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Ekun_sky 2016-12-18
  • 打赏
  • 举报
回复
with st(id,code) as (
select 1,'A001' union all
select 1,'A002' union all
select 2,'A003' union all
select 3,'A004' union all
select 3,'A005')



select id,code=stuff((select ','+code from st as a where a.id=st.id for xml path('')),1,1,'') from st group by id


/*
id    code
--------------
1	A001,A002
2	A003
3	A004,A005
*/
卖水果的net 版主 2016-12-18
  • 打赏
  • 举报
回复

-- 你自己把最后的 逗号去掉吧

create table test(id int, code varchar(10))
go
insert into test values
(1, 'A001'),(1, 'A002'),(2, 'A003'),(3, 'A004'),(3, 'A005')
go
select id ,
(select code + ',' from test where id = t.id for xml path('') ) code
from test t
group by id 
go
drop table test 
go


(5 行受影响)
id          code
----------- --------------------------
1           A001,A002,
2           A003,
3           A004,A005,

(3 行受影响)


34,571

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧