id,name,bm
1 a 01
1 a 02
2 b 01
3 c 01
如何写sql语句取出这样的记录集合,即把id,name 相同的bm放到同一行?
id,name,bm
1 a 01 02
2 b 01
3 c 01
1 a 01
1 a 02
2 b 01
3 c 01
如何写sql语句取出这样的记录集合,即把id,name 相同的bm放到同一行?
id,name,bm
1 a 01 02
2 b 01
3 c 01
解决方案 »
- sql高手看过来,一个很棘手的问题寻帮助
- <NULL>的疑问?
- 自动代理运行job ,远程运行存储过程,中继过程 错误!
- 求助,各位帮帮我,看看代码错在哪里?
- 存储过程中怎么把1变成001
- ALTER 修改字段默认值的错误?
- SQL server服务无法启动:17052:SQL Server evaluation period has expired
- 是SQL的BUG吗?大侠看看到底是怎么回事
- SQL SERVER 2000服务器出问题了!求救!
- 高分!一条sql语句的小问题。(在线,解决马上给分儿!)
- 这个数学题目的答案是什么??????????????????????????
- 准备做一个大型购物网站,需要建几个表
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 table tb
(
a int,
b int
)
insert into tb(a,b) values(1,1)
insert into tb(a,b) values(1,2)
insert into tb(a,b) values(1,3)
insert into tb(a,b) values(2,1)
insert into tb(a,b) values(2,2)
insert into tb(a,b) values(3,1)
go--创建一个合并的函数
create function f_hb(@a int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + ',' + cast(b as varchar) from tb where a = @a
set @str = right(@str , len(@str) - 1)
return(@str)
End
go--调用自定义函数得到结果:
select distinct a ,dbo.f_hb(a) as b from tbdrop table tb--结果
a b
----------- ------
1 1,2,3
2 1,2
3 1(所影响的行数为 3 行)
1 a 01 02
2 b 01
3 c 01
--创建一个合并的函数
create function f_hb(@id int,@name varchar)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + '''+ ''' + cast(bm as varchar) from tb where id = @id and name=@name
set @str = right(@str , len(@str) - 1)
return(@str)
End
go--调用自定义函数得到结果:
select distinct id , name ,dbo.f_hb(id , name) as bm from tb
drop table tb
gocreate table tb
(
id int,
name varchar(10),
bm varchar(10)
)
insert into tb(id,name,bm) values(1,'a','01')
insert into tb(id,name,bm) values(1,'a','02')
insert into tb(id,name,bm) values(2,'b','01')
insert into tb(id,name,bm) values(3,'c','01')
go
--创建一个合并的函数
if object_id('pubs..f_hb') is not null
drop table f_hb
go
create function f_hb(@id int,@name varchar)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + ' ' + cast(bm as varchar) from tb where id = @id and name=@name
set @str = right(@str , len(@str) - 1)
return(@str)
End
go--调用自定义函数得到结果:
select distinct id , name ,dbo.f_hb(id , name) as bm from tbdrop table tb
drop function f_hbid name bm
----------- ---------- -----
1 a 01 02
2 b 01
3 c 01(所影响的行数为 3 行)