7

我正在使用 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 操作消除。”

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

  1. 关闭 ANSI_WARNINGS
  2. 分成两个查询,一个带有 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
    
  3. 忽略客户端中的警告

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

4

4 回答 4

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

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

于 2009-05-12T09:29:58.930 回答
2

任何可能返回 null 的地方,请使用

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

这将在查询期间将所有 Null 值替换为 -1 并且它们将被计算/聚合,然后你可以在你的精细包装查询中做相反的事情......

SELECT  
    CASE WHEN t1.a = -1 THEN NULL ELSE t1.a END as a
    , t1.countdistinctb
    , t2.suma
于 2009-05-12T08:00:44.427 回答
2

这是一个迟到的笔记,但由于它是谷歌的回报,我想提一下。

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

COUNT() 正在这样做,而不是 DISTINCT。

相反,在子查询中使用 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(因为它计算记录,而不是值)。

于 2011-10-25T18:37:09.193 回答
1

如果您不喜欢代码重复,那么为什么不使用公用表表达式呢?例如

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
于 2009-05-12T09:41:19.193 回答