0

I tried for hours and read many posts but I still can't figure out how to handle this request:

I have a table like this:

+------+------+
|roleid|comid |
+------+------+
|11    | A    |
+------+------+
|12    | A    |
+------+------+
|11    |B     |
+------+------+
|12    |B     |
+------+------+
|13    |B     |
+------+------+

I would like to select the roleid that occurs more than once with the different comid.

I wanna output should be something like:

+------+------+
|roleid|comid |
+------+------+
|11    |A,B   |
+------+------+
|12    |A,B   |
+------+------+
|13    |B     |
+------+------+
0

2 Answers 2

1

Simply, you can use STUFF() function with FOR XML PATH('') as

SELECT roleid,
       STUFF(
         (
           SELECT ',' + comid
           FROM T
           WHERE roleid = T1.roleid
           FOR XML PATH('')
         ), 1, 1, ''
       ) comid 
FROM T T1
GROUP BY roleid

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

If you are using SQL Server version greater than or equal to 2017, you can use also STRING_AGG function and to take only those roleids having more than one distinct comid you have to use HAVING caluse:

SELECT roleid,
       STRING_AGG(comid, ',')
FROM T
GROUP BY roleid
HAVING COUNT(DISTINCT comid) > 1

1 Comment

I'm using SQL Server 2017 but the error is occur i.e. 'STRING_AGG' is not a recognized built-in function name.

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.