4

我试图找到所有具有相同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
-------------- ---------------
排除零 2
NoRows 3
两个结果 2

当我期望我的输出是

groupCol distinctInfoCol
-------------- ---------------
两个结果 2
三结果 3
二与零 2

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

4

1 回答 1

4
select groupCol, count(distinct infoCol) as distinctInfoCol 
from #t 
where infoCol <> 0
group by groupCol
having count(distinct infoCol) > 1
于 2012-10-31T23:46:32.357 回答