question

prntcena avatar image
prntcena asked

How to restructure sql table from table1 to table 2 like this.

Table1 is like this

Id Name Subject

1 Rakesh English

1 Rakesh Maths

1 Rakesh Science

2 Mukesh English

2 Mukesh Maths

Table 2 which I want is like this:

Id Name Subject

1 Rakesh English, Maths, Science

2 Mukesh English, Maths

sqldatabasemysqljoin
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Kev Riley avatar image
Kev Riley answered

If you are using SQL 2017 or newer, you can use the STRING_AGG() function

select
	id, [name],
	string_agg(Subject,',') as [subject]
from Table1
group by
 id, Name

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.