SQL Help: Select statement Concatenate a One to Many relationship

后端 未结 8 1693
天涯浪人
天涯浪人 2021-01-03 16:28

For example I have two tables. The first table is student while the second table are the courses that the a student is taking. How can I use a select statement so that I can

8条回答
  •  攒了一身酷
    2021-01-03 17:02

    create table Project (ProjectId int, Description varchar(50));
    insert into Project values (1, 'Chase tail, change directions');
    insert into Project values (2, 'ping-pong ball in clothes dryer');
    
    create table ProjectResource (ProjectId int, ResourceId int, Name varchar(15));
    insert into ProjectResource values (1, 1, 'Adam');
    insert into ProjectResource values (1, 2, 'Kerry');
    insert into ProjectResource values (1, 3, 'Tom');
    insert into ProjectResource values (2, 4, 'David');
    insert into ProjectResource values (2, 5, 'Jeff');
    
    SELECT *, 
      (SELECT Name + ' ' AS [text()] 
       FROM ProjectResource pr 
       WHERE pr.ProjectId = p.ProjectId 
       FOR XML PATH ('')) 
    AS ResourceList 
    FROM Project p
    
    --    ProjectId    Description                        ResourceList
    --    1            Chase tail, change directions      Adam Kerry Tom 
    --    2            ping-pong ball in clothes dryer    David Jeff 
    

提交回复
热议问题