Blog

Code snippets etc

Aggregate concatenation in TSQL

When rolling up data using Group By one of the things that has been missing in TSQL is the ability to concatenate. You can SUM, MAX, MIN etc...but no concatenation.  There are various methods that will get you over the line, but they always feel like hacks.  Starting in SQL vNext (Version after SQL 2016) we finally get a solution. The example below will work in Azure or if you are running the very latest version. It will not work in SQL 2016.

 

------------------------------------------------------------------------------------------------------
--Declare and fill a names table for example
------------------------------------------------------------------------------------------------------

DECLARE @names TABLE
(
FirstName VARCHAR(100)
,
LastName VARCHAR(100)
)

INSERT INTO @names
SELECT 'Jamie' AS FirstName, 'Lannister' AS LastName
UNION
SELECT
'Tyrion' AS FirstName, 'Lannister' AS LastName
UNION
SELECT
'Tywin' AS FirstName, 'Lannister' AS LastName
UNION
SELECT
'Eddard' AS FirstName, 'Stark' AS LastName
UNION
SELECT
'Sansa' AS FirstName, 'Stark' AS LastName
UNION
SELECT
'Arya' AS FirstName, 'Stark' AS LastName
UNION
SELECT
'Robb' AS FirstName, 'Stark' AS LastName

SELECT * FROM @names ORDER BY LastName, FirstName


------------------------------------------------------------------------------------------------------
--The old way...one of many 
------------------------------------------------------------------------------------------------------

SELECT     t.LastName
          
, COUNT(*) AS FirstNameCount
          
,STUFF((
              
SELECT ',' + t1.FirstName
              
FROM @names t1
              
WHERE t1.LastName = t.LastName
              
FOR XML path(''), TYPE
          
).value('.', 'varchar(max)'), 1, 1, '') FirstNameConcat
FROM       @names t
GROUP BY    t.LastName

------------------------------------------------------------------------------------------------------
--The new way in SQL vNext (Version after 2016)
------------------------------------------------------------------------------------------------------
SELECT     t.LastName
          
,COUNT(*) AS FirstNameCount
          
,STRING_AGG(FirstName, ',') WITHIN GROUP (ORDER BY FirstName ASC)  AS FirstNameConcat
FROM       @names t
GROUP BY    t.LastName

by Richard Grieveson

BANANA