SQL Help: Select statement Concatenate a One to Many relationship

后端 未结 8 1692
天涯浪人
天涯浪人 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:17

    Assuming you're using SQL Server 2005:

    This should do what you're after - obviously replace fields as you need:

    For demo purposes, consider the following two table structures:

    Students(
      STU_PKEY Int Identity(1,1) Constraint PK_Students_StuPKey Primary Key,
      STU_NAME nvarchar(64)
    )
    
    Courses(
      CRS_PKEY Int Identity(1, 1) Constraint PK_Courses_CrsPKey Primary Key,
      STU_KEY Int Constraint FK_Students_StuPKey Foreign Key References Students(STU_PKEY),
      CRS_NAME nvarchar(64)
    )
    

    Now this query should do the job you're after:

    Select  s.STU_PKEY, s.STU_NAME As Student,
            Stuff((
                Select  ',' + c.CRS_NAME
                From    Courses c
                Where   s.STU_PKEY = c.STU_KEY
                For     XML Path('')
            ), 1, 1, '') As Courses 
    From    Students s
    Group By s.STU_PKEY, s.STU_NAME
    

    Way simpler than the currently accepted answer...

    0 讨论(0)
  • 2021-01-03 17:18

    You can use a UDF that cursors through the related records and concats a return string together but this will be expensive - if you give it a go make sure your cursor is READ_ONLY FAST_FORWARD

    0 讨论(0)
提交回复
热议问题