Sql-server – How to get one row out of many rows with same column id

queryrowsql server

I have a use case in which I have three tables.

Courses Table

Course_ Id   Name
 1   MathMatics
 2   Physics

Teacher Table

 Teacher_ID  Teacher_Name
    1    AAA
    2    BBB

TeacherVsCourses Table

 id  Course_id  Teacher_id 
 1   1   1
 2   2   1
 3   1   2

My application is programmed using the MVC design pattern of ASP.NET. I am saving individual records into the database table as shown below:

enter image description here


What I want in my view is instead of two rows for Teacher-id=1, I need 1 row with comma separated courses.

How can I achieve this?

Best Answer

You can return a comma separated list of values by using the string_agg function.

https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15