按查询分组不返回我的预期

时间:2012-10-31 23:39:17

标签: 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),      ('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

我做错了什么,如何更正以获得我需要的结果?

1 个答案:

答案 0 :(得分:4)

select groupCol, count(distinct infoCol) as distinctInfoCol 
from #t 
where infoCol <> 0
group by groupCol
having count(distinct infoCol) > 1