我有两个“一对多”表:
表格1
ID Name 1 Abe 2 David 3 Orly
表2
ID email 1 a@zz.com 1 ab@zz.com 1 abe@zz.com 2 dav@zz.com 2 d@zz.com 3 orly@zz.com 3 o@zz.com
我需要这样的输出:
1 Abe a@zz.com, ab@zz.com, abe@zz.com 2 David dav@zz.com, d@zz.com 3 Orly orly@zz.com, o@zz.com
我知道这行不通,因为内部SELECT不是单个字符串:
SELECT ID, Name, (SELECT email FROM Table2 WHERE Table2.ID = Table1.ID) AS emails FROM Table1
我尝试申请:
DECLARE @emails VARCHAR(999) SELECT [ID],[Name], (SELECT @emails = COALESCE(@emails + ', ', '') + [email] FROM Table2) AS 'emails' FROM Table1
但没有运气。
应该如何解决呢?
谢谢。
实现这一目标的最巧妙的方法之一是将For XML Path和STUFF结合如下:
SELECT ID, Name, Emails = STUFF(( SELECT ', ' + Email FROM Table2 WHERE Table2.ID = Table1.ID FOR XML PATH ('')),1,2,'') FROM Table1