I have a table in SQL Server with the following layout and some sample data:
| ReferenceNumber | TagID |
+-----------------+-------+
| 114942 | 1 |
| 114942 | 2 |
| 114942 | 3 |
| 114942 | 4 |
| 123456 | 10 |
Is it possible to consolidate like ReferenceNumber rows into a single row, so:
| ReferenceNumber | TagID |
+-----------------+---------+
| 114942 | 1,2,3,4 |
| 123456 | 10 |
I've tried:
select
ReferenceNumber,
stuff((select '; ' + TagID from RefTagTable
for xml path('')), 1, 1,'')[Tags]
from
RefTagTable
order by
ReferenceNumber
which outputs:
| ReferenceNumber | Tags |
+-----------------+------------+
| 114942 | 1,2,3,4,10 |
| 123456 | 1,2,3,4,10 |
Any help would be greatly appreciated. Thanks
GROUP BY. In SQL Server 2017 and later you can useSTRING_AGGfor this. In earlier versionsFOR XMLwith an empty tag name is used to emulate the same effect. In SQL Server 2017 you can writeSELECT RefNumber, STRING_AGG(',',Tag) from RefTagTable GROUP BY RefNumber