Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server sql server的sql查询组_Sql Server_Sql Server 2008_Tsql_Sql Server 2008 R2 - Fatal编程技术网

Sql server sql server的sql查询组

Sql server sql server的sql查询组,sql-server,sql-server-2008,tsql,sql-server-2008-r2,Sql Server,Sql Server 2008,Tsql,Sql Server 2008 R2,我有一个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, Cou

我有一个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
我不知道如何在查询中也包含错误ID
有人能告诉我怎么解决这个问题吗?

作为一名武士,我本以为你能解决这个问题。:)您是否尝试过声明游标并逐行构建字符串?本质上,你的问题是使用N行的解决方案并返回逗号分隔的字符串。是的,我知道。我考虑过把我的名字改成SQL初学者。。但是那些名字已经被取了。感谢您的解决方案:-)
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