我使用的是 SQL Server 2005。使用下面的查询(根据我的真实查询进行简化):
select a,count(distinct b),sum(a) from
(select 1 a,1 b union all
select 2,2 union all
select 2,null union all
select 3,3 union all
select 3,null union all
select 3,null) a
group by a
有没有什么方法可以在不重复的情况下进行计数
“警告:空值会被聚合或其他 SET 操作消除。”
以下是我能想到的替代方案:
- 关闭 ANSI_WARNINGS
分为两个查询,一个查询包含不同计数,一个 where 子句用于消除空值,一个查询包含总和:
select t1.a, t1.countdistinctb, t2.suma from ( select a,count(distinct b) countdistinctb from ( select 1 a,1 b union all select 2,2 union all select 2,null union all select 3,3 union all select 3,null union all select 3,null ) a where a.b is not null group by a ) t1 left join ( select a,sum(a) suma from ( select 1 a,1 b union all select 2,2 union all select 2,null union all select 3,3 union all select 3,null union all select 3,null ) a group by a ) t2 on t1.a=t2.a
忽略客户端中的警告
有更好的方法吗?我可能会选择路线 2,但不喜欢代码重复。
最佳答案
select a,count(distinct isnull(b,-1))-sum(distinct case when b is null then 1 else 0 end),sum(a) from
(select 1 a,1 b union all
select 2,2 union all
select 2,null union all
select 3,3 union all
select 3,null union all
select 3,null) a
group by a
多亏了 Eoin,我找到了一种方法来做到这一点。您可以对包括空值在内的不同值进行计数,然后使用不同值之和删除由于空值而导致的计数(如果有)。
关于sql - 计算不同值并通过聚合消除 Null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/851642/