Table structure. The data is as follows:
ID value
-- ---------
1 AA
1 Bb
2 Aaa
2 Bbb
2 CCC
Expected results:
IDValues
-----------------
1AA, BB
2Aaa, BBB, CCC
That is:Group ByID, calculate the sum of values (string addition)
1 . Old solution (in SQL Server 2000, only functions can be used .)
-- 1. Create a processing function
Create Table TB (ID Int , Value Varchar ( 10 ))
Insert Into TB Values ( 1 , ' AA ' )
Insert Into TB Values ( 1 , ' Bb ' )
Insert Into TB Values ( 2 , ' Aaa ' )
Insert Into TB Values ( 2 , ' Bbb ' )
Insert Into TB Values ( 2 , ' CCC ' )
Go
Create Function DBO. f_str ( @ ID Int )
Returns Varchar ( 8000 )
As
Begin
Declare @ R Varchar ( 8000 )
Set @ R = ''
Select @ R = @ R + ' , ' + Value From TB Where ID = @ ID
Return Stuff ( @ R , 1 , 1 , '' )
End
Go
--Call a function
SelectID, Value=DBO. f_str (ID)FromTBGroup ByID
Drop TableTB
Drop FunctionDBO. f_str
/*
ID value
----------------------
1 aa, BB
2 AAA, BBB, CCC
(The number of affected rows is 2)
*/
-- 2. Another function.
Create Table TB (ID Int , Value Varchar ( 10 ))
Insert Into TB Values ( 1 , ' AA ' )
Insert Into TB Values ( 1 , ' Bb ' )
Insert Into TB Values ( 2 , ' Aaa ' )
Insert Into TB Values ( 2 , ' Bbb ' )
Insert Into TB Values ( 2 , ' CCC ' )
Go
-- Create a merged Function
Create Function F_hb ( @ ID Int )
Returns Varchar ( 8000 )
As
Begin
Declare @ Str Varchar ( 8000 )
Set @ Str = ''
Select @ Str = @ Str + ' , ' + Cast (Value As Varchar ) From TB Where ID = @ ID
Set @ Str = Right ( @ Str , Len ( @ Str ) - 1 )
Return ( @ Str )
End
Go
--Call the custom function to obtain the result:
Select DistinctID, DBO. f_hb (ID)AsValueFromTB
Drop TableTB
Drop FunctionDBO. f_hb
/*
id value
----------- ---------
1 aa, BB
2 AAA, BBB, CCC
(the number of affected rows is 2)
*/