Skip to content
Advertisement

Concatenate from rows in SQL server

I want to concatenate from multiple rows

Table:

|id      |Attribute   |Value    |
|--------|------------|---------|
|101     |Manager     |Rudolf   |
|101     |Account     |456      |
|101     |Code        |B        |
|102     |Manager     |Anna     |
|102     |Cardno      |123      |
|102     |Code        |B        |
|102     |Code        |C        |

The result I’m looking for is:

|id      |Manager|Account|Cardno|Code      |
|--------|-------|-------|------|----------|
|101     |Rudolf |456    |      |B         |
|102     |Anna   |       |123   |B,C       |

I have the following code from a related question:

However, it fails for the Code attribute with ID# 102, where both B and C values are present.

How can I update this to include both of those values in the same result?

Advertisement

Answer

If you are using SQL SERVER 2017 or above then string_agg() with PIVOT() will be easy to use but much faster in performance solution (Query#1).

If you are using older version of SQL Server then go for Query#2 with STUFF() and XML PATH FOR() for concatenating value along with PIVOT()

Schema:

Query#1 PIVOT() with STRING_AGG():

Output:

id manager account cardno code
101 Rudolf 456 <emnull</em B
102 Anna <emnull</em 123 B,C

Query#2 PIVOT() WITH STUFF() AND XML PATH FOR():

Output:

id manager account cardno code
101 Rudolf 456 <emnull</em B
102 Anna <emnull</em 123 B, C

db<fiddle here

Advertisement