How to get multiple rows into one line as a string?

后端 未结 2 559
傲寒
傲寒 2020-12-13 21:47

I have two tables \"one to many\":

Table1

ID    Name
1     Abe
2     David
3     Orly

Table2

ID    email
1     a@zz         


        
2条回答
  •  自闭症患者
    2020-12-13 22:05

    One of the neatest ways to achieve this is to combine For XML Path and STUFF as follows:

    SELECT
        ID, Name, 
        Emails = STUFF((
            SELECT ', ' + Email FROM Table2 WHERE Table2.ID = Table1.ID
            FOR XML PATH ('')),1,2,'')
    FROM Table1
    

提交回复
热议问题