代码之家  ›  专栏  ›  技术社区  ›  Simon D

计数不同,Null值被聚合消除

  •  7
  • Simon D  · 技术社区  · 17 年前

    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
    

    1. 关闭ANSI_WARNINGS
    2. 分为两个查询,一个带有count distinct和where子句以消除null,另一个带有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
      

    有更好的方法吗?我可能会走第二条路,但不喜欢代码重复。

    4 回复  |  直到 17 年前
        1
  •  7
  •   Simon D    17 年前
    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
    

        2
  •  2
  •   Eoin Campbell    17 年前

    CASE WHEN Column IS NULL THEN -1 ELSE Column END AS Column
    

    这将在查询期间为-1分配所有空值,并按此方式进行计数/聚合,然后您可以在精细包装查询中执行相反的操作。..

    SELECT  
        CASE WHEN t1.a = -1 THEN NULL ELSE t1.a END as a
        , t1.countdistinctb
        , t2.suma
    
        3
  •  2
  •   onof    15 年前

    将NULL更改为另一个值是一个坏主意(tm)。

    相反,在子查询中使用DISTINCT,它返回一个数字,并在外部查询中聚合该数字。

    一个简单的例子是:

    WITH A(A) AS (SELECT NULL UNION ALL SELECT NULL UNION ALL SELECT 1)
    SELECT COUNT(*) FROM (SELECT DISTINCT A FROM A) B;
    

    COUNT(*) 它不会忽略NULL(因为它计算的是记录,而不是值)。

        4
  •  1
  •   onedaywhen    17 年前

    如果你不喜欢代码重复,那么为什么不使用一个通用的表表达式呢?例如

    WITH x(a, b) AS 
            (
                    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
            ) 
    select t1.a, t1.countdistinctb, t2.suma from
    (
            select a,count(distinct b) countdistinctb from 
            x a
            where a.b is not null
            group by a
    ) t1
    left join
    (
            select a,sum(a) suma from 
            x a
            group by a
    ) t2 on t1.a=t2.a