Skip to content
Advertisement

Concat based on sequence number

I’m trying to concat a text field based on a separate field and sequence number. For this example let’s say the fields I have are employee ID, Sequence#, and Comments. The comments field is limited by a certain number of characters so there can be multiple comment fields for the same employee ID sorted by the sequence number. I would like to get 1 line per employee ID and concat all the comments together into one.

Current Data

Expected Data

Advertisement

Answer

What @zohar posted is how I would do it with SQL 2017+. On Pre-2017 systems you’ll have to go the XML PATH route.

Returns:

To protect against special XML characters (a problem STRING_AGG does not have) you would append the code to look like this:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement