Reputation: 21
I have the following table in SQL Server
Names TypeID
-------------
JJ 23
KK 20
LL 15
JJ 13
KK 18
JJ 10
I want the results of my select query to appear as below
Names TypeID
---------------
JJ 23,13,10
KK 20,18
LL 15
How can i achieve this? Please help, am new to sql
Upvotes: 0
Views: 80
Reputation: 325
try this
SELECT Names, TypeID =
STUFF((SELECT ', ' + Convert(nvarchar(2),TypeID)
FROM your_table b
WHERE b.Names = a.Names
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY Names
Upvotes: 0
Reputation: 7189
drop table #t
create table #t(names varchar(10),type1 int)
insert into #t values('JJ',23),
('KK',20),
('LL',15),
('JJ',13),
('KK',18),
('JJ',10)
select distinct names,stuff((select ',' +cast(type1 as varchar(10)) from #t t2 where t2.names=t1.names for xml path('') ),1,1,'') as TypeID
from #t t1
Upvotes: 1
Reputation: 27
try this code
SELECT name, GROUP_CONCAT(typeid)
FROM test
GROUP BY name
Upvotes: -1
Reputation: 2826
This question was answered many times before. For example here: Does T-SQL have an aggregate function to concatenate strings?
A good code snippet is like this:
set nocount on;
declare @YourTable table (RowID int, HeaderValue int, ChildValue varchar(5))
insert into @YourTable VALUES (1,1,'CCC')
insert into @YourTable VALUES (2,2,'B<&>B')
insert into @YourTable VALUES (3,2,'AAA')
insert into @YourTable VALUES (4,3,'<br>')
insert into @YourTable VALUES (5,3,'A & Z')
set nocount off
SELECT
t1.HeaderValue
,STUFF(
(SELECT
', ' + t2.ChildValue
FROM @YourTable t2
WHERE t1.HeaderValue=t2.HeaderValue
ORDER BY t2.ChildValue
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
) AS ChildValues
FROM @YourTable t1
GROUP BY t1.HeaderValue
This code is taken from the same thread to which I've posted link.
Upvotes: 2
Reputation: 13509
Try this:-
SELECT Names, GROUP_CONCAT(TypeID)
FROM YOUR_TABLE
GROUP BY Names;
Upvotes: 0