SOLVED - Pivot a result set
-
I need to create a subquery that pulls detail records for the header records in the main query. But I'd like to display values from the detail records in the form of a comma separated list, like so, "value1, value2, value3". And this list should appear as an extra column in the result set. Is there any way to achieve this in SQL Server? SOLUTION: Use the STRING_AGG function! Cool.
The difficult we do right away... ...the impossible takes slightly longer.
-
I need to create a subquery that pulls detail records for the header records in the main query. But I'd like to display values from the detail records in the form of a comma separated list, like so, "value1, value2, value3". And this list should appear as an extra column in the result set. Is there any way to achieve this in SQL Server? SOLUTION: Use the STRING_AGG function! Cool.
The difficult we do right away... ...the impossible takes slightly longer.
STRING_AGG
is the best approach for SQL Server 2017 or later. If you need to support earlier versions, you'll need an alternative: Concatenating Row Values in Transact-SQL - Simple Talk[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer