Skip to content

SQL - SQL Server - Concatenate Strings

Source: sql-snippets/concatenate-strings.md at main · count/sql-snippets (github.com)

Explore this snippet here.

Description

Use the STRING_AGG function to concatenate strings within a group. To specify the ordering, make sure to use the WITHIN GROUP clause too.

with data as (
  select * from (values
    ('A', '1'),
    ('A', '2'),
    ('B', '3'),
    ('B', '4'),
    ('B', '5')
  ) as data(str, num)
)

select
  str,
  string_agg(num, ' < ') within group (order by num asc) as aggregated
from data
group by str

Output:

str aggregated
A 1 \< 2
B 3 \< 4 \< 5

Backlinks:

list from [[SQL - SQL Server - Concatenate Strings]] AND -"Changelog"