1

我有一个Emaildistributionlist包含 3 列的表:UnitID这是唯一的,Email并且dept Name. 在这里,我编写了一个查询来获取基于的列表id

SELECT distinct id, EMAIL 
FROM tblEmaildistributionlist  
WHERE dept like '%Contracts Dept%'

所以我得到如下输出:

 ID=1  Email="cc@gmail.com" etc...

但问题是一个 id 有很多电子邮件,所以我想要一个像这样的输出

ID=1 Email=cc@gmail.com,rr@gmail.com,yy@gmail.com.` 

所有emailid's 以逗号分隔的形式,在电子邮件列中。

我需要在查询中进行哪些修改才能获得此结果?

4

3 回答 3

3

这项工作适用于 Mysql

SELECT 
     id, 
     GROUP_CONCAT(distinct EMAIL SEPARATOR ',') as Email 
from 
     tblEmaildistributionlist 
WHERE 
     dept like '%Contracts Dept%' 
GROUP BY 
     id

这适用于 SQL Server

SELECT
    a.id,
    STUFF((SELECT ','+b.Email From tblEmaildistributionlist b WHERE b.id=a.id AND b.dept like '%Contracts Dept%' FOR XML PATH ('')),1,1,'') as Email
FROM 
    tblEmaildistributionlist a
WHERE 
    a.dept like '%Contracts Dept%' 
GROUP BY
    a.id

这适用于 Oracle 11g

SELECT 
     id, 
     LISTAGG(EMAIL, ',') as Email 
from 
     tblEmaildistributionlist 
WHERE 
     dept like '%Contracts Dept%' 
GROUP BY 
     id
于 2012-05-07T08:40:03.617 回答
2

你可以用这个。它工作正常

DECLARE @listStr VARCHAR(MAX) SELECT @listStr = COALESCE(@listStr+',' , '') + EmailId FROM StudentDetails SELECT @listStr

像这样发出 - email@doamin.com,emaol1@domain.com

于 2013-09-06T06:42:54.463 回答
0
    select  a.ID,Stuff((select distinct  ','+ b.EMAIL from tblEmaildistributionlist b 
   where b.ID=a.ID and b.dept like '%Contracts Dept%' FOR XML PATH ('')  ),1,1,'') AS EMAIL
     from  tblEmaildistributionlist a
    WHERE 
     a.dept like '%Contracts Dept%'
     group by a.ID

完美运行....

于 2012-05-08T08:18:02.013 回答