SQL将所有空值计数为不同

时间:2019-06-07 20:50:02

标签: sql

我需要编写一个查询,告诉我有多少(COUNT)个唯一客户购买了$ 200以上的商品。我的表有一个customer_id,purchase_id和total。 purchase_id对于每一行都是唯一的。 Customer_id可以重复,也可以有空值。

“唯一客户被认为是唯一的customer_id或空的customer_id。因此在列表中:

1
2
1
null
null
null

将有5个唯一客户。

6 个答案:

答案 0 :(得分:0)

此SQL应该给您结果

select (select count(distinct customer_id)) + 
       (select count(*) from a where customer_id is null)
  from your table

答案 1 :(得分:0)

这可以做到:

select
  count(distinct customer_id) + 
  count(case when customer_id is null then 1 end) as counter
from tablename 
where total > 200

第一个count()将对所有不同的非null customer_id进行计数,第二个count()将对空值进行计数。

答案 2 :(得分:0)

您需要进行过滤器内部查询并使用union allDistinct仅在客户ID不为null时获取一次。另一方面,您将每个空值都计为单独的客户。下面的查询将为您提供帮助。

select count(*) from (
   select distinct customerid 
    from table_name 
   where customerid is not null 
         and total > 200 
    union all 
   select customerid 
    from table name 
    where customerid is null 
      and total>200)

答案 3 :(得分:0)

SELECT (
(SELECT COUNT DISTINCT customer_id FROM TABLE where total > 200 and customer_id IS NOT NULL) +
(SELECT COUNT customer_id FROM TABLE where total > 200 and customer_id IS NULL)
)

答案 4 :(得分:0)

您可以使用简单的SQL来做到这一点。

SELECT customer_id, count(*) AS count
FROM t1
WHERE total > 200
GROUP BY customer_id

或者获得简单的唯一客户数...

SELECT count(*) AS totalUniqueCustomers
FROM (
  SELECT customer_id
  FROM t1
  WHERE total > 200
  GROUP BY customer_id
) s1

SQL Fiddle

MS SQL Server 2017架构设置

CREATE TABLE t1 (purchase_id int IDENTITY, customer_id int, total int);

INSERT INTO t1 (customer_id, total)
VALUES 
      (1, 202)
    , (2, 250)
    , (1, 10)
    , (null, 1000)
    , (null, 20)
    , (null, 500)
    , (3, 10)
;
/* NOTE: I added orders with both over and under the 200 mark to show excluding 
   the ones you don't want. */

查询1

SELECT customer_id, count(*) AS count
FROM t1
WHERE total > 200
GROUP BY customer_id

Results

| customer_id | count |
|-------------|-------|
|      (null) |     2 |
|           1 |     1 |
|           2 |     1 |

查询2

/* TO GET A SIMPLE COUNT OF UNIQUE CUSTOMERS */
SELECT count(*) AS totalUniqueCustomers
FROM (
  SELECT customer_id
  FROM t1
  WHERE total > 200
  GROUP BY customer_id
) s1

Results

| totalUniqueCustomers |
|----------------------|
|                    3 |

答案 5 :(得分:0)

只需:

select count(distinct customer_id) + sum(case when customer_id is null then 1 else 0 end)
from t;

count(distinct)计算不同的非NULL值的数量。第二个增加了NULL的数量。

在某些数据库中,您可以简化第二个表达式。例如,在MySQL中:

select count(distinct customer_id) + sum( customer_id is null )
from t;