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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Tripati Subudhi
  • 1,651
  • 10
  • 22
  • 26

3 Answers3

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

Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
  • 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!! – GrayFox374 Jun 20 '12 at 20:06
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
SP007
  • 1,871
  • 1
  • 22
  • 31
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
Community
  • 1
  • 1
Marek Grzenkowicz
  • 17,024
  • 9
  • 81
  • 111