我正在使用 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
分成两个查询,一个带有 count distinct 和一个 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 走,但不喜欢代码重复。