求一種這樣的sql寫法

zhuqiang9 2006-12-08 08:56:03
id why
1 a
1 b
1 c
2 d
2 b

----result
id why
1 a+b+c
2 d+b


這種類型的sql,誰可以幫助我實現謝謝
...全文
91 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
marco08 2006-12-08
  • 打赏
  • 举报
回复

create table T(id int, why char(1))
insert T select 1, 'a'
union all select 1, 'b'
union all select 1, 'c'
union all select 2, 'd'
union all select 2, 'b'

create function fun(@id int)
returns varchar(1000)
as
begin
declare @re varchar(1000)
set @re=''
select @re=@re+why+'+' from T where id=@id
set @re=left(@re, len(@re)-1)

return @re
end

select id, dbo.fun(id) as Why from T group by id

--result
id Why
----------- -------------------
1 a+b+c
2 d+b

(2 row(s) affected)
caixia615 2006-12-08
  • 打赏
  • 举报
回复
create table tb
(
id int,
why char(10)
)
insert into tb(id,why) values(1,'a')
insert into tb(id,why) values(1,'b')
insert into tb(id,why) values(1,'c')
insert into tb(id,why) values(2,'d')
insert into tb(id,why) values(2,'b')

go

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

--调用自定义函数得到结果:
select distinct id,why=dbo.f_hb(id) from tb

drop table tb
冷箫轻笛 2006-12-08
  • 打赏
  • 举报
回复
--创建用户定义函数
create function f_str(@id int)
returns varchar(8000)
as
begin
declare @ret varchar(8000)
set @ret = ''
select @ret = @ret+'+'+why from 表 where id = @id
set @ret = stuff(@ret,1,1,'')
return @ret
end
go


--执行
select id,why=dbo.f_str(id) from 表 group by id order by id
go

34,591

社区成员

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

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