Click here to Skip to main content
15,897,226 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i have this table

---------
ID | Name
--------
1 | A1
2 | A2
3 | A3
1 | B1
2 | B2
3 | B3
---------

i wanna get this table from up table :

---------
ID | Name
--------
1 | A1 - B1
2 | A2 - B2
3 | A3 - B3
---------

please guide me ...
Posted

1 solution

Use a join

SQL
select t1.ID, t1.name + '-' + t2.name from myTable t1 JOIN myTable t2 ON(t1.ID = t2.ID)



SQL
SELECT ID,
       REPLACE(RTRIM((SELECT Name + ' ' FROM myTable
                      WHERE (ID = t.ID)
                      FOR XML PATH (''))),' ',' - ')
FROM myTable t
GROUP BY ID
 
Share this answer
 
v3
Comments
vahid_erad 14-Oct-11 12:14pm    
what am i for this table :
---------
ID | Name
--------
1 | A1
2 | A2
3 | A3
1 | B1
2 | B2
1 | C1
---------

get table :

---------
ID | Name
--------
1 | A1 - B1 - C1
2 | A2 - B2
3 | A3
---------
Simon Bang Terkildsen 14-Oct-11 12:23pm    
Updated the solution
vahid_erad 14-Oct-11 14:02pm    
this query :
SELECT ID,
REPLACE(RTRIM(SELECT Name + ' ' FROM myTable
WHERE (ID = t.ID)
FOR XML PATH ('')),' ',' - ')
FROM myTable t
GROUP BY ID


Have this errors :
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ')'.
Simon Bang Terkildsen 14-Oct-11 14:34pm    
If you had tried to play around with it you would have found out that there were missing a parenthesis set around the inner select.
The solution is updated.
Espen Harlinn 15-Oct-11 4:21am    
Good reply :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900