尝试在前两个圆圈的交叉点中计算不同的人数。 (在图中我试图得到标记为d的区域的计数)。键1,2和3属于第一个圆,4,5,6属于第二个圆,7,8,9,10属于第三个圆。
表结构如下:
customer key
A234 1
A345 4
A12 5
A989 6
这是我试过的查询:
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
答案 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;