Column connection under GROUP BY statement in SQL
In SQL, a common way to combine or join columns based on a GROUP BY statement is to use aggregate functions in conjunction with string operators. Let's explore how to achieve this.
Consider the following example table:
ID | 用户 | 活动 | 页面URL |
---|---|---|---|
1 | 我 | act1 | ab |
2 | 我 | act1 | cd |
3 | 你 | act2 | xy |
4 | 你 | act2 | st |
To concatenate the PageURL values for each user and activity group separated by commas, we can use the following query:
SELECT [user], activity, STUFF((SELECT ',' page URL FROM table name WHERE [user] = a. [user] AND activity = a. activity FOR XML PATH ('')) , 1, 1, '') AS URL list FROM table name AS a GROUP BY [user], activity
Query breakdown:
The generated table will have the desired layout:
用户 | 活动 | URL列表 |
---|---|---|
我 | act1 | ab, cd |
你 | act2 | xy, st |
This approach leverages the power of aggregate functions and string operations to effectively concatenate column values based on GROUP BY operations, making it a flexible solution for a variety of data manipulation tasks.
The above is the detailed content of How to Concatenate Columns Based on GROUP BY in SQL?. For more information, please follow other related articles on the PHP Chinese website!