大力帮忙,难题

cgq214 2004-04-14 08:06:39
eg2:
有表A,
id pid
1 1
1 2
1 3
2 1
2 2
3 1
如何化成表B:
id pid
1 1,2,3
2 1,2
3 1

--1.创建一个合并的函数
create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=''
select @str=@str+','+cast(pid as varchar) from 表A where id=@id
set @str=right(@str,len(@str)-1)
return(@str)
End
go

--调用自定义函数得到结果
select distinct id,dbo.fmerg(id) from 表A

现在我要实现
有表A,
id pid
1 1
1 2
1 3
2 1
2 2
3 1
如何化成表B:
id a1 a2 a3
1 1 2 3
2 1 2
3 1
问大家如何解决
...全文
43 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2004-04-14
  • 打赏
  • 举报
回复
declare @s varchar(8000)
set @s=''
select @s=@s+',[a'+cast(pid as varchar)+']=max(case pid when '
+cast(pid as varchar)+' then cast(pid as varchar) else '' end)'
from 表a group by id
exec('select id'+@s+' from 表a group by id')

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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