求教一个SQL查询语句的写法

ego 2006-10-24 04:48:52
库记录如下:
ID fieldB
2 'A'
2 'B'
3 'A'
3 'B'
2 'C'
如何写SQL查询语句得到这样的结果?
2 'ABC'
3 'AB'
...全文
227 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Well 2006-10-24
  • 打赏
  • 举报
回复
写一个返回字符串的function
传递的参数为ID,
中国风 2006-10-24
  • 打赏
  • 举报
回复
create table roy_a(
ID int ,fieldB varchar(20))
insert roy_a
select 2, 'A' union all
select 2, 'B' union all
select 3, 'A' union all
select 3, 'B' union all
select 2, 'C'

create function roy_b(@id int)
returns varchar(1000)
as
begin
declare @sql varchar(1000)
set @sql=''
select @sql=@sql+fieldB+'/' from roy_a where [id]=@id
select @sql=left(@sql,len(@sql)-1)
return @sql
end

select id,fieldB=dbo.roy_b(id)from roy_a group by id
id fieldB
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2 A/B/C
3 A/B

(所影响的行数为 2 行)


中国风 2006-10-24
  • 打赏
  • 举报
回复
楼主,SQL2000要用函数,SQL2005不用函数
dawugui 2006-10-24
  • 打赏
  • 举报
回复
SQL语句之合并行列转换

  有表rowtocol,其数据如下:
  a b
  1 1
  1 2
  1 3
  2 1
  2 2
  3 1
  如何转换成如下结果:
  a b
  1 1,2,3
  2 1,2
  3 1

  创建一个合并的函数   

  create function f_rowtocol(@a int)
  returns varchar(8000)
  as
  begin
   declare @str varchar(8000)
   set @str = ''
   select @str = @str + ',' + cast(b as varchar) from rowtocol where a = @a
   set @str = right(@str , len(@str) - 1)
   return(@str)
  End
  go


  调用自定义函数得到结果:
  select distinct a ,dbo.f_rowtocol(a) from rowtocol
i9988 2006-10-24
  • 打赏
  • 举报
回复
--未测试
i9988 2006-10-24
  • 打赏
  • 举报
回复
函数

create function fn_fieldB(
@id int
)
returns
varchar(200)
as
begin
declare
@r varchar(200)
set
@r=''
select
@r=@r+fieldB
from
tablename
where
id=@id
return
@r
end
go

--调用
select
id,
dbo.fn_fieldB(id) as fieldB
from
tablename
group by
id

34,588

社区成员

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

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