See the following table: AggregationTable
Id |
Name |
1 |
Zhao |
2 |
Money |
1 |
Sun |
1 |
Li |
2 |
Week |
If you want to obtain the aggregation result
Id |
Name |
1 |
Zhao Sun Li |
2 |
Qian Zhou |
SUM, AVG, COUNT, COUNT (*), MAX, and MIN cannot be used. These are the aggregation of values. However, we can solve this problem through user-defined functions.
1. First create a test table and insert the test data:
Copy codeThe Code is as follows:
Create table AggregationTable (Id int, [Name] varchar (10 ))
Go
Insert into AggregationTable
Select 1, 'zhao 'union all
Select 2, 'money' union all
Select 1, 'sun' union all
Select 1, 'lil' union all
Select 2, 'Week'
Go
2. Create a custom string Aggregate Function
Copy codeThe Code is as follows:
Create FUNCTION aggresponstring
(
@ Id int
)
RETURNS varchar (1024)
AS
BEGIN
Declare @ Str varchar (1024)
Set @ Str =''
Select @ Str = @ Str + [Name] from AggregationTable
Where [Id] = @ Id
Return @ Str
END
GO
3. Execute the following statement and view the result.
Copy codeThe Code is as follows:
Select dbo. aggresponstring (Id), Id from AggregationTable
Group by Id
Result:
Id |
Name |
1 |
Zhao Sun Li |
2 |
Qian Zhou |