如何使 SQL 有条件地请求 COUNT DISTINCT?

How to make SQL request COUNT DISTINCT with conditions?

我有 table 个包含

的互动

Table样本:

datetime       | CustomerID | Segment | Response
---------------+------------+---------+---------
20181126000001 | 1          | A       | Accept  
20181126000005 | 1          | A       | Ignore  
20181126000010 | 2          | B       | Ignore  
20181126000015 | 3          | A       | Accept  

我的任务是发出请求,使不同的客户计数符合条件:

  1. 计数属于细分市场的客户 'A';
  2. 如果细分 'A' 中没有客户,则统计所有客户。

所以在伪代码中我想做这样的事情:

CASE
    WHEN 
        (select count distinct CustomerID from INTERACTIONS where Segment = 'A') = 0 
    THEN 
        (select count distinct CustomerID from INTERACTIONS)
    ELSE
        (select count distinct CustomerID from INTERACTIONS where Segment = 'A')
END

预期结果 - 单一值。在此示例中,结果 = 2.

你能帮忙把完整的请求写到数据库吗?

你可以试试下面

select 
CASE
    WHEN count(distinct case when Segment = 'A' then CustomerID end)=0 THEN count(distinct CustomerID)
    ELSE
        count(distinct case when Segment = 'A' then CustomerID end)
from INTERACTIONS

可以用子查询来实现(避免二次计算)

SELECT CASE WHEN T.customer_a > 0 THEN customer_a ELSE customer_all FROM
(
   SELECT 
       (SELECT count(distinct customer_id) FROM INTERACTIONS WHERE segment = 'A') AS customer_a,        
       (SELECT count(distinct customer_id) FROM INTERACTIONS) AS customer_all   )
) AS T

有一个 派生的 table(子查询),您在其中使用 case 表达式来执行 条件聚合统计A段客户,统计所有客户。

select case when acnt > 0 then acnt else allcnt end
from
(
    select count(distinct case when segment = 'A' then CustomerID end) acnt,
           count(distinct CustomerID) allcnt
    from INTERACTIONS
) dt