查询以查找三个不同类的交集

时间:2017-06-23 15:23:21

标签: sql hive

尝试在前两个圆圈的交叉点中计算不同的人数。 (在图中我试图得到标记为d的区域的计数)。键1,2和3属于第一个圆,4,5,6属于第二个圆,7,8,9,10属于第三个圆。

表结构如下:

customer       key
A234            1
A345            4
A12             5
A989            6

enter image description here

这是我试过的查询:

      select count(distinct(c.key))
      from (select c.key
        from tab1 c
        group by c.key
        having sum(case when key1 in (1,2,3) then 1 else 0 end) > 0 and
               sum(case when key1 in (4,5,6,7,8) then 1 else 0 end) = 0
      ) c

1 个答案:

答案 0 :(得分:1)

我认为你只是让你的HAVING条款混淆了。

select count(*)
from 
(
  select key
  from tab1
  group by key
  having sum(case when key1 in (1,2,3) then 1 else 0 end) > 0 -- in circle A
     and sum(case when key1 in (4,5,6) then 1 else 0 end) > 0 -- in circle B
     and sum(case when key1 in (7,8,9,10) then 1 else 0 end) = 0 -- not in circle C
) region_d;
相关问题