I have a table of data:
|Key|Field |DateField |
|A |Value1|2012-06-01|
|A |Value2|2012-06-02|
|A |Value3|2012-06-03|
|B |Value4|2012-06-04|
|B |Value5|2012-06-05|
I want to aggregate this string data by key – like in a group but I can’t work out how.
What I want to end up with is:
|Key|Field Aggregate |
|A |Value1, Value2, Value3|
|B |Value4, Value5 |
Better still would be to end up with the sequence position inserted into the aggregation where the order of the sequence is determined by the order of the corresponding date field.
|Key|Field Aggregate |
|A |1: Value1, 2: Value2, 3: Value3|
|B |1: Value4, 2: Value5 |
This seems like something I could do with a Common Table Expression, but I don’t seem to be able to work out how.
I wouldn’t ordinarily perform this kind of operation in SQL – I’d normally pull the data into an app and manipulate it as necessary in code.
Unfortunately this does not appear to be an option in this instance.
How can I do this in SQL Server 2005 T-SQL.
Is a CTE the right approach? Is there something more appropriate?
Given this sample data:
In versions of SQL Server older than SQL Server 2017, we can do this:
Results:
In SQL Server 2017 or greater, we have a much easier time using
STRING_AGG():