我试图找到所有具有相同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
我做错了什么,我该如何纠正以获得我需要的结果?