0

Below I have shown two tables and also the result table.

enter image description here

How can I get the result table in this manner as I shown on above?

1

3 Answers 3

6
select min(ID) as ID,
       Val,
       stuff((select ','+Cat
              from Table2 as T2
              where T1.Val = T2.Val
              for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as Cat
from Table2 as T1
group by Val
order by ID

SQL Fiddle

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

1 Comment

WOW. That's impressive. It's gone to take me a bit to parse it, but it works, inline, no clr, no scalar functions needed. And now I know about SQL fiddle. Twofer!!
0
DECLARE @Table1 TABLE
( 
 id INT
 ,Val VARCHAR(100)
)
DECLARE @Table2 TABLE
(
id INT
,Val VARCHAR(100)
,Cat VARCHAR(100)
)

INSERT INTO @Table1
VALUES(1,'XYZ')

INSERT INTO @Table1
VALUES(2,'abc')

INSERT INTO @Table2
VALUES(1,'XYZ','a')

INSERT INTO @Table2
VALUES(1,'abc','e')

INSERT INTO @Table2
VALUES(1,'XYZ','b')

INSERT INTO @Table2
VALUES(1,'XYZ','f')

INSERT INTO @Table2
VALUES(1,'abc','g')


SELECT t1.id,t1.Val ,( SELECT STUFF((SELECT ',' + cat  FROM @Table2 t2 WHERE  t2.Val =                   t1.val FOR XML PATH('')),1,1,''))
 FROM   @Table1 t1

Comments

0

You can define a CLR user-defined aggregate to do it. I posted a detailed description of such a solution as an answer to another question - TSQL Comma Separation. There you'll also find a link to a blog post that discusses the problems you may encounter while developing a CLR aggregate.

After you deploy the custom aggregate to the server (I named the function Concat but yours may be named differently), you will be able to obtain the required result with the following query:

SELECT Val, dbo.Concat(Cat)
FROM Table2
GROUP BY Val

Comments

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.