1

我有一个 sql server 数据库表,其列如下所示:

表格1

Id Name ErrorId
1   AB     
2   CD    
3   AB    3
4   AB    4

我想得到这样的输出:

Name IdCount   ErrorIdCount  ErrorIds
AB      3           2           4,3 
CD      1           0            0

我写了一个查询,目前看起来像这样:

select Name, Count(Id) as IdCount, 
Count(Distinct case when ErrorId != ' ' then Id END) as ErrorIdCount
from Table1 
group by Name;

它给了我下面这样的东西:

Name IdCount ErrorIdCount.
AB      3        2
CD      1        0

我无法弄清楚如何在我的查询中也包含ErrorIds?谁能指出我该如何解决这个问题?

4

1 回答 1

2
Declare @a table (Id int, Name varchar(10),ErrorId int)
insert into @a Values (1,'AB',null),(2,'CD',null),(3,'AB',3),(4,'AB',4);


Select Name, Count(Id) as IdCount, 
Count(Distinct case when ErrorId != ' ' then Id END) as ErrorIdCount
,[ErrorIds]=
STUFF((SELECT ', ' + Cast(ErrorId as Varchar(10))
    FROM @a iup           
    WHERE iup.Name = a.Name 
    order by  ErrorId  
    FOR XML PATH('')), 1, 1, '') 
from @a a
Group by Name
于 2013-06-05T18:46:06.637 回答