0

In SQL Server, I have a query pulling values like:

SELECT ID, NAME, TITLE
FROM TABLE_X

To get results like:

ID  NAME  TITLE
----------------
01  Bob   Cat
02  Bob   Bat
03  Tom   Mat

I want to run a query to get the following results:

NAME  COUNT  TITLE
-----------------------
Bob   2      Cat, Bat
Tom   1      Mat

All I have is something like this:

SELECT NAME, COUNT(ID), STUFF(TITLE)
FROM TABLE_X

2 Answers 2

1

The STUFF syntax will be as shown in this below code to get your desired result-

SELECT B.NAME, COUNT(*) [COUNT],
STUFF((
    SELECT  ',' + A.TITLE 
    FROM TABLE_X A 
    WHERE A.NAME = B.NAME  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') TITLE
FROM TABLE_X B
GROUP BY  B.NAME

Output is-

NAME    COUNT   TITLE
Bob     2       Cat,Bat
Tom     1       Mat
Sign up to request clarification or add additional context in comments.

Comments

0

You can group by NAME and use the STRING_AGG aggregate function (starting with SQL Server 2017)

SELECT NAME, COUNT(*) AS [COUNT], STRING_AGG(TABLE_X.TITLE, ', ') AS TITLE
FROM TABLE_X
GROUP BY NAME
ORDER BY NAME

Note that only the columns listed in the GROUP BY clause can appear as-is in the SELECT list. You must apply an aggregate function to all the others. I escaped the column alias COUNT, as this is a reserved word.

6 Comments

'STRING_AGG' is not a recognized built-in function name.
This function was added in SQL Server 2017.
I have SQL Server Management Studio v17.9.1 and that was the error they were giving me :/
It does not depend on the version of the Management Studio, it depends on the version of the DB Server.
SELECT @@VERSION to get the SQL-Server Version
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.