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

时间:2018-11-28 10:12:09

标签: sql count db2 case distinct

我的表INTERACTIONS包含

  • 日期时间,
  • 客户ID
  • 客户群(“ A”组或“ B”组)
  • 客户回应。

表示例:

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。

您能帮忙将完整的请求写入数据库吗?

3 个答案:

答案 0 :(得分:2)

具有一个(子查询),在该表中,您使用case表达式进行条件聚合来计算细分客户并计算所有客户

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

答案 1 :(得分:1)

您可以在下面尝试

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

答案 2 :(得分:0)

您可以通过子查询来做到这一点(避免两次计算)

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