SQL Count在一列中重复,但重复的条件不仅是一个固定值

tim*_*guy 6 sql oracle conditional count

我试过搜索其他帖子,但只能找到关于一个固定值的重复.

想象一下下表:

 ????????????????????
 ? customer ? color ?
 ????????????????????
 ?        1 ? black ?
 ?        1 ? black ?
 ?        2 ? red   ?
 ?        2 ? black ?
 ?        3 ? red   ?
 ?        3 ? red   ?
 ?        3 ? red   ?
 ?        4 ? black ?
 ?        5 ? black ?
 ?        5 ? green ?
 ?        6 ? purple?
 ????????????????????
Run Code Online (Sandbox Code Playgroud)

我想选择"重复"意味着以下客户:

  • 有一个以上的黑色
  • 一个黑色和其他红色也是一个副本
  • 没有重复:客户可以拥有他想要的红色数量

到目前为止我有什么

目前我可以选择的只是关于黑色复制品,但我不能将它与"一个黑色,不再是红色"的条件结合起来.

SELECT customer FROM events WHERE
    color = 'black'
    group by customer
    having count(*) > 1
Run Code Online (Sandbox Code Playgroud)

也许我可以先计算黑人,然后再加入现有的桌子计算额外的黑人和红人?

期望的输出

我希望得到以下结果作为客户:1,2.更好的是一个输出,我知道客户是双黑色还是黑色+一些红色:

???????????????????????????????????????
? customer ? blackOnly ? blackPlusRed ?
???????????????????????????????????????
?        1 ? yes       ? no           ?
?        2 ? no        ? yes          ?
???????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

抱歉,我不得不修改我的帖子

  • 我在示例表中添加了客户5和6以及更多颜色.所以也许一些建议不再适用:-(.(只想快速编辑,所以如果我没有遵循一些修改规则,请告诉我)
  • 感谢迄今为止非常快速的答案

Tho*_*ner 1

您希望所有客户都有“黑色”且至少有两条记录。您可以通过条件聚合来做到这一点:

select 
  customer,  
  case when count(distinct color) = 1 then 'yes' else 'no' end as blackOnly,
  case when count(distinct color) > 1 then 'yes' else 'no' end as blackPlusRed
from events 
group by customer
having count(*) > 1
and count(case when color = 'black' then 1 end) > 0;
Run Code Online (Sandbox Code Playgroud)

更新:如果允许其他颜色,查询会略有变化:

select 
  customer,  
  case when count(case when color = 'red' then 1 end) = 0 then 'yes' else 'no' end as blackOnly,
  case when count(case when color = 'red' then 1 end) > 0 then 'yes' else 'no' end as blackPlusRed
from events 
group by customer
having count(case when color = 'black' then 1 end) > 1
or
(
  count(case when color = 'black' then 1 end) > 0
  and 
  count(case when color = 'red' then 1 end) > 0
);
Run Code Online (Sandbox Code Playgroud)