SQL Server String Aggregate functions

Source: Internet
Author: User
SqlServer has the following Aggregate functions: SUM, AVG, COUNT, COUNT (*), MAX, and MIN. However, all these functions can only aggregate numeric types and cannot aggregate strings.

SQL Server has the following Aggregate functions: SUM, AVG, COUNT, COUNT (*), MAX, and MIN. However, these functions can only aggregate value types and cannot aggregate strings.

See the following table: AggregationTable

If you want to obtain the aggregation result

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:
The 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
The 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.
The Code is as follows:
Select dbo. aggresponstring (Id), Id from AggregationTable
Group by Id

Result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.