📅  最后修改于: 2023-12-03 15:31:04.702000             🧑  作者: Mango
SQL Server offers the GROUP_CONCAT function, which aggregates the values of a column into a single string separated by a separator. This function is useful in scenarios where you need to combine multiple rows into a single row based on a common attribute.
The syntax for the GROUP_CONCAT function is as follows:
GROUP_CONCAT(expression [, separator])
Where expression is the column, expression or value to concatenate, and separator is an optional parameter that specifies the separator character between concatenated values, which can be any valid string value.
Let's consider the following table that contains customer data:
| CustomerID | FirstName | LastName | PhoneNumber | |---|---|---|---| | 101 | James | Smith | 123-456-7890 | | 102 | Mary | Johnson | 555-555-5555 | | 103 | John | Doe | 111-111-1111 |
If we want to get a single row for all customers, we can use the GROUP_CONCAT function as follows:
SELECT GROUP_CONCAT(FirstName + ' ' + LastName) as FullName, GROUP_CONCAT(PhoneNumber, ', ') as PhoneNumbers
FROM Customers
This will return the following result:
| FullName | PhoneNumbers | |---|---| | James Smith, Mary Johnson, John Doe | 123-456-7890, 555-555-5555, 111-111-1111 |
The GROUP_CONCAT function has some limitations that you should be aware of:
The GROUP_CONCAT function in SQL Server is a handy tool for concatenating strings from different rows into a single row. With the optional separator, you can control the formatting of the concatenated string. However, you should be aware of the limitations of this function and choose an appropriate alternative when needed.