-1

Hi i have a table like some "Demo" in that i have two Columns (ID,Name),

I have table:

enter image description here

I want to get table like:

enter image description here

How Can i write sql query for this ?

--TIA

Ben805
  • 59
  • 2
  • 15
  • Depends on the server. Ms-SQL has `stuff()/for xml` (see [here](https://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/)), mysql has [group_concat](http://www.sqlines.com/mysql/functions/group_concat) and oracle has [listagg](http://stackoverflow.com/a/16771200/515948) – Laur Ivan Jan 31 '17 at 07:03

3 Answers3

0

You have to use group by clause with group_concat() like:

select Id, group_concat(name) as name
from Demo
group by Id;

here group by Id will make groups of data on id bases and group_concat() function concatenate the name.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
0
SELECT DISTINCT id AS uqId, (SELECT GROUP_CONCAT(name_col) FROM table WHERE id = uqId) AS NAME FROM table;

try this query. This might help you.

0
Begin TRAN
CREATE TABLE #temp(Id INt,Event Nvarchar(25))
INSERT INTO #temp
SELECT 1,'IND'UNION ALL
SELECT 1,'USA'UNION ALL
SELECT 1,'AUS'UNION ALL
SELECT 1,'RUS'UNION ALL
SELECT 2,'DUBAI'UNION ALL
SELECT 2,'UK'UNION ALL
SELECT 3,'JAPAN'


SELECT DISTINCT ID,  STUFF(
             (   SELECT ',' + [EVENT] 
                 FROM #temp t1
                 WHERE ID = y.ID
                 FOR XML PATH (''))
             , 1, 1, '') 
FROM #temp y


ROLLBACK TRAN
Alfaiz Ahmed
  • 1,698
  • 1
  • 11
  • 17