How to combine multiple columns into one single row and aggregate the strings into list or one string

Mahlangu, Neo N 20 Reputation points
2023-09-14T20:18:25.22+00:00

How to combine multiple columns into one single row . eg if you have two columns in a table called name, surname, and location.

neo hlophi london

peter lock asia

bernad jules asia

result :

I want to have name and surname combined by a dash e.g : neo|hlophi in a new column called combination.

location combination

london neo|hlophi

asia peter|lock,bernad|jules

SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,702 questions
Microsoft Security Microsoft Graph
SQL Server Other
{count} votes

Accepted answer
  1. Naomi Nosonovsky 8,431 Reputation points
    2023-09-14T20:44:40.2233333+00:00

    Try (SQL Server 2017 and up):

    DECLARE @t TABLE (name varchar(30), surname VARCHAR(30), location VARCHAR(30)) 
    INSERT INTO @t (name, surname, location) 
    VALUES 	('neo', 'hlophi', 'london'), 	('peter', 'lock', 'asia'), 	('bernad', 'jules', 'asia') 
    
    
    SELECT location, STRING_AGG(CONCAT(name, '|', surname),',') FROM @t GROUP BY location
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-09-14T21:37:22.06+00:00
    SELECT concat(localtion, ' ', name, '|', surename)
    FROM  tbl
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.