Reputation: 1645
Right now my sql query display the result as follows. though it is the correct result.
I prefer to have the have the result to show as follows. How can I do this with SQL ? I am on SQL server 2008
Upvotes: 0
Views: 85
Reputation: 34784
I'm with the commenters, better to do this elsewhere, but it's simple enough in SQL using a CASE
statement and the ROW_NUMBER()
function:
;WITH cte AS (SELECT *,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY (SELECT 1)) RN
FROM YourTable)
SELECT CASE WHEN RN = 1 THEN CAST(ID AS VARCHAR(5)) ELSE '' END, Name
FROM cte
ORDER BY ID,RN
Demo: SQL Fiddle
Upvotes: 3
Reputation: 7009
This is not a job for SQL.
Any way, you can easily display it with comma separated values:
ID Names
1000 Honda, Toyota,...
1000 Honda, Toyota,...
SELECT ID, Names=
STUFF((SELECT ', ' + Name
FROM your_table b
WHERE b.ID= a.ID
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ID
Upvotes: 1