STRING_AGG Function in SQL Server

This function is introduced in SQL Server 2017 (14x) concatenates the values of string expressions and places separator values between them. The separator is not added at the end of the string.

STRING_AGG

For practice, use the dataset below. Each student is assigned three subjects. One input per student is required, with all of his chosen subjects listed in a single row separated by a comma.

StudentName Subject
Scott Mathematics
Scott Physics
Scott Chemistry
Williams Mathematics
Williams Physics
Williams Chemistry
Mary Mathematics
Mary Physics
Mary Chemistry
Mike Mathematics
Mike Physics
Mike Chemistry
John Mathematics
John Physics
John Chemistry
George Mathematics
George Physics
George Chemistry


Implementation:

SELECT  StudentName,
              STRING_AGG(Subjects,’,’) Subjects
FROM tbStudentInfo
GROUP BY
    StudentName;

Result:

StudentName Subjects
Scott Mathematics, Physics, Chemistry
Williams Mathematics, Physics, Chemistry
Mary Mathematics, Physics, Chemistry
Mike Mathematics, Physics, Chemistry
John Mathematics, Physics, Chemistry
George Mathematics, Physics, Chemistry

Hope you find this article helpful.

Please subscribe for more interesting updates.

4 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s