计算distinct和Null值由聚合消除

Sim*_*n D 7 sql sql-server null aggregate sql-server-2005

我正在使用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
Run Code Online (Sandbox Code Playgroud)

有什么方法可以在没有得到的情况下进行计数

"警告:聚合或其他SET操作消除了空值."

以下是我能想到的替代方案:

  1. 关闭ANSI_WARNINGS
  2. 分成两个查询,一个是count distinct,一个是where子句来消除空值,一个是sum:

    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
    
    Run Code Online (Sandbox Code Playgroud)
  3. 忽略客户端中的警告

有一个更好的方法吗?我可能会沿着路线2前进,但不喜欢代码重复.

Sim*_*n D 6

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
Run Code Online (Sandbox Code Playgroud)

感谢Eoin,我找到了一种方法来做到这一点.您可以计算不同的值,包括空值,然后删除由于空值计数,如果有任何使用不同的和.