我有两个表“一对多”:
表格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,Emails = STUFF(( SELECT ',' + Email FROM Table2 WHERE Table2.ID = Table1.ID FOR XML PATH ('')),1,2,'') FROM Table1