Using STRING_AGG to Concatenate Employee Names
Use STRING_AGG to Concatenate Strings
Write a SQL query to concatenate employee names within each department into a single string.
Solution:
-- Concatenate employee names within each department.
SELECT
DepartmentID,
STRING_AGG(Name, ', ') AS EmployeeNames
FROM Employees
GROUP BY DepartmentID;
Explanation:
- The goal is to demonstrate how to use STRING_AGG to concatenate strings (e.g., employee names) within groups (e.g., departments).
- STRING_AGG(Name, ', ') : Concatenates employee names, separated by a comma.
- GROUP BY DepartmentID : Groups employees by department.
- STRING_AGG simplifies string concatenation across rows, replacing older methods like FOR XML PATH.
- For example, in reporting systems, you might use this query to generate a list of employees grouped by department.
- Ensure that the delimiter (e.g., , ) is appropriate for the context.
- Use this exercise to teach how to aggregate strings efficiently.
- Write a SQL query to concatenate product names within each category into a single string separated by semicolons.
- Write a SQL query to generate a comma-separated list of all customers in each region.
- Write a SQL query to create a summary of skills possessed by employees in each department.
- Write a SQL query to concatenate all tags associated with blog posts into a single string.
1. Purpose of the Query :
2. Key Components :
3. Why use STRING_AGG? :
4. Real-World Application :
Additional Notes:
For more Practice: Solve these Related Problems:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise: Use PERCENT_RANK and CUME_DIST Functions.
Next SQL Exercise: Handle JSON Arrays with Nested Queries.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics