gpt4 book ai didi

sql - 按查询分组没有返回我期望的结果

转载 作者:行者123 更新时间:2023-12-02 00:55:49 26 4
gpt4 key购买 nike

我正在尝试查找具有相同 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   2NoRows         3TwoResults     2

当我期望我的输出是

groupCol       distinctInfoCol-------------- ---------------TwoResults     2ThreeResults   3TwoAndZero     2

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

最佳答案

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

关于sql - 按查询分组没有返回我期望的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13168965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com