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

如何进行记录合并,高手请进
现有如下记录
510 计算机
511 计算机
512 计算机
512 摄像机
512 相机
513 U盘
514 U盘
515 计算机

合并后应是

510 计算机
511 计算机
512 计算机,摄像机,相机
513 U盘
514 U盘
515 计算机

请问如何写类似的SQL语句啊?

------解决方案--------------------
寫個合併函數。

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
*/
------解决方案--------------------

--合併函數

Create Table TEST
(ID Int,
Name Nvarchar(10))
Insert TEST Select 510, N '计算机 '
Union All Select 511, N '计算机 '
Union All Select 512, N '计算机 '
Union All Select 512, N '摄像机 '
Union All Select 512, N '相机 '
Union All Select 513, N 'U盘 '
Union All Select 514, N 'U盘 '
Union All Select 515, N '计算机 '
GO
Create Function GetName(@ID Int)
Returns Nvarchar(4000)
As
Begin
Declare @S Nvarchar(4000)
Select @S = ' '
Select @S = @S + ', ' + Rtrim(Name) From TEST Where ID = @ID
Select @S = Stuff(@S , 1, 1 , ' ')
Return @S
End
GO
Select
ID,
dbo.GetName(ID) As Name
From
TEST
Group By
ID
GO
Drop Table TEST
Drop Function GetName
--Result
/*
ID Name
510 计算机
511 计算机
512 计算机,摄像机,相机
513 U盘
514 U盘
515 计算机
*/
------解决方案--------------------
在SQL2000中只能使用函數實現,如果是SQL2005,就可以不用函數。

參考此貼中老大的寫法。

http://community.csdn.net/Expert/topic/4800/4800752.xml?temp=.9653742
------解决方案--------------------
Create Table t(id Int,c2 Int)
Insert t Select 510, '计算机 '
Union All Select 511, '计算机 '
Union All Select 512, '计算机 '
Union All Select 512, '摄像机 '
Union All Select 512, '相机 '
Union All Select 513, 'U盘 '
Union All Select 514, 'U盘 '
Union All Select 515, '摄像机 '


create Function f1(@id Int)
Returns Varchar(8000)
As
Begin
Declare @str Varchar(8000)
Select @str = ' '
Select @str = @str + ', ' + Rtrim(c2) From t Where id = @id
Select @str = Stuff(@str , 1, 1 , ' ')
Return @str
End
GO
Select id dbo.f1(id)
From t
Group By id
------解决方案--------------------
create table ta( id int,name varchar(20))
insert ta select 510, '计算机 '
insert ta select 511, '计算机 '
insert ta select 512, '计算机 '
insert ta select 512, '摄像机 '
insert ta select 512, '相机 '