我有两张桌子“一对多”:
表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
但没有运气。
如何解决这个问题?
感谢。
答案 0 :(得分:28)
实现此目标的最佳方法之一是将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
答案 1 :(得分:8)
SELECT *
FROM Table1 a
CROSS APPLY --or OUTER APPLY
(
SELECT SUBSTRING(
(SELECT ','+b.Email
FROM Table2 b
WHERE a.ID = b.ID
FOR XML PATH(''))
,2
,4000) GroupConcat
) x
结果:
ID Name GroupConcat
-- ----- -----------------------------
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