日期:2014-05-18  浏览次数:20622 次

求一个SQL合并语句,急,
在数据表中有如下内容
name         odrer
ASD               D
ASD               G
ASD               J
DFG               D
DRT               K
现在想得到另一个数据表如下
name1           odrer1
ASD               D,G,J
DFG               D
DRT               K
也就是相同的NAME在一行显示,后面跟上ORDER的值,谢谢!

------解决方案--------------------
用函数的,抄一个给你~~~

--测试数据
create table csdn(id int,txt varchar(10))
insert csdn
select 1, 'a ' union all
select 1, 'b ' union all
select 1, 'c ' union all
select 2, 'aa ' union all
select 2, 'bb ' union all
select 2, 'cc ' union all
select 3, 'aaa ' union all
select 3, 'bbb '
select * from csdn
go

create function Gettxt(@id int)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s= ' '
select @s=@s + ', ' +txt from csdn where id=@id
--return @s
return stuff(@s,1,1, ' ')
end
go

select id,dbo.Gettxt(id) txt from csdn group by id
go

drop function Gettxt
drop table csdn
go
------解决方案--------------------
eg:

Create Table TEST
(aaa Int,
bbbb Int,
amount Int)
Insert TEST Select 111, 222, 333
Union All Select 222, 222, 444
Union All Select 111, 333, 555
Union All Select 111, 222, 777
GO
Create Function Getamount(@aaa Int, @bbbb Int)
Returns Varchar(8000)
As
Begin
Declare @S Varchar(8000)
Select @S = ' '
Select @S = @S + ', ' + Rtrim(amount) From TEST Where aaa = @aaa And bbbb = @bbbb
Select @S = Stuff(@S , 1, 1 , ' ')
Return @S
End
GO
Select
aaa,
bbbb,
dbo.Getamount(aaa, bbbb) As amount
From
TEST
Group By aaa, bbbb
GO
Drop Table TEST
Drop Function Getamount
--Result
/*
aaa bbbb amount
111 222 333,777
111 333 555
222 222 444
*/
------解决方案--------------------
--带符号合并行列转换

--有表t,其数据如下:
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

if object_id( 'pubs..f_hb ') is not null
drop function f_hb
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 tb

drop table tb

--结果
a b
----------- ------
1