String Aggregation and Pivoting Techniques in SQL Server

Introduction to String Aggregation String aggregation (or string concatenation) is a common requirement in SQL reporting where you need to combine multiple row values into a single string. SQL Server provides several powerful techniques for this operation, each with its own strengths. Traditional String Aggregation Methods 1. FOR XML PATH Method (Pre-SQL Server 2017) SELECT DepartmentID, STUFF(( SELECT ', ' + EmployeeName FROM Employees e2 WHERE e2.DepartmentID = e1.DepartmentID FOR XML PATH('') ), 1, 2, '') AS EmployeeList FROM Employees e1 GROUP BY DepartmentID; 2. COALESCE with Variable Concatenation DECLARE @EmployeeList VARCHAR(MAX) = ''; SELECT @EmployeeList = @EmployeeList + EmployeeName + ', ' FROM Employees WHERE DepartmentID = 5; -- Remove trailing comma SET @EmployeeList = LEFT(@EmployeeList, LEN(@EmployeeList) - 1); SELECT @EmployeeList; Modern String Aggregation (SQL Server 2017+...