Sql Group by查询没有返回我所期望的结果
我正在尝试查找具有相同groupCol但有多个非0 infoCol的所有记录。这是一个完整的例子,我正在尝试做什么Sql Group by查询没有返回我所期望的结果,sql,sql-server,sql-server-2005,Sql,Sql Server,Sql Server 2005,我正在尝试查找具有相同groupCol但有多个非0 infoCol的所有记录。这是一个完整的例子,我正在尝试做什么 CREATE TABLE #t ( groupCol varchar(14) NOT NULL, infoCol int NOT NULL, indexCol int NOT NULL IDENTITY (1, 1) ) GO insert into #t (groupCol, infoCol) values ('NoRows',1),
CREATE TABLE #t
(
groupCol varchar(14) NOT NULL,
infoCol int NOT NULL,
indexCol int NOT NULL IDENTITY (1, 1)
)
GO
insert into #t (groupCol, infoCol)
values ('NoRows',1), ('NoRows',1), ('NoRows',1), --Not in output due to having only 1 disticnt infoCol
('TwoResults',1), ('TwoResults',1), ('TwoResults',2), --In the output with "'TwoResults', 2"
('ThreeResults',1),('ThreeResults',2),('ThreeResults',3), --In the output with "'ThreeResults', 3"
('ExcludedZero',1),('ExcludedZero',1),('ExcludedZero',0) --Not in the output due to 0 being excluded for finding distinct infoCol's
('TwoAndZero',1), ('TwoAndZero',2), ('TwoAndZero',0) --In the output but returns 2 not 3.
select * from #t
select groupCol, count(groupCol) as distinctInfoCol
from #t
where infoCol <> 0
group by groupCol, infoCol
having count(groupCol) > 1
drop table #t
然而,我的查询结果是
groupCol distinctInfoCol
-------------- ---------------
ExcludedZero 2
NoRows 3
TwoResults 2
当我期望我的输出是
groupCol distinctInfoCol
-------------- ---------------
TwoResults 2
ThreeResults 3
TwoAndZero 2
我做错了什么,如何更正此错误以获得所需的结果?我想如果我想要一个不同的计数,我应该指定一个不同的计数。谢谢你教我可以在计数内使用。
select groupCol, count(distinct infoCol) as distinctInfoCol
from #t
where infoCol <> 0
group by groupCol
having count(distinct infoCol) > 1