SQL 在一列中计算重复项,但重复项的条件不是只有一个固定值

SQL Count duplicates in one column but condition for duplicate is not only one fixed value

我尝试搜索其他 post,但只能找到关于找到一个固定值的重复项。

想象一下 table:

 ╔══════════╦═══════╗
 ║ customer ║ color ║
 ╠══════════╬═══════╣
 ║        1 ║ black ║
 ║        1 ║ black ║
 ║        2 ║ red   ║
 ║        2 ║ black ║
 ║        3 ║ red   ║
 ║        3 ║ red   ║
 ║        3 ║ red   ║
 ║        4 ║ black ║
 ║        5 ║ black ║
 ║        5 ║ green ║
 ║        6 ║ purple║
 ╚══════════╩═══════╝

我要select"duplicates"表示以下客户:

到目前为止我有什么

目前我能做的 select 只是关于黑色副本,但我不能将它与条件 "one black, no more red".

结合起来
SELECT customer FROM events WHERE
    color = 'black'
    group by customer
    having count(*) > 1

也许我可以先数黑人,然后再加入现有的 table 数额外的黑人和红人?

期望的输出

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

╔══════════╦═══════════╦══════════════╗
║ customer ║ blackOnly ║ blackPlusRed ║
╠══════════╬═══════════╬══════════════╣
║        1 ║ yes       ║ no           ║
║        2 ║ no        ║ yes          ║
╚══════════╩═══════════╩══════════════╝

抱歉不得不修改我的 post

您希望所有客户都有 'black' 和至少两条记录。您可以使用条件聚合来做到这一点:

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;

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

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
);

这个查询首先创建一个临时的 table 包含每个客户的黑色和红色的计数,然后查询这个 table 以获得 blackOnlyblackPlusRed每个客户的列值。

SELECT t.customer,
    CASE WHEN t.black > 1 AND t.red = 0 THEN 'yes' ELSE 'no' END AS blackOnly,
    CASE WHEN t.black > 0 AND t.red > 0 THEN 'yes' ELSE 'no' END AS blackPlusRed
FROM
(
    SELECT *,
        SUM(CASE WHEN color='black' THEN 1 ELSE 0 END) AS black,
        SUM(CASE WHEN color='red' THEN 1 ELSE 0 END) AS red
    FROM events
    GROUP BY customer
) t

如果您想添加新的颜色条件,例如只有红色,那么你可以在外部查询中添加一个新的 CASE 语句:

CASE WHEN t.red > 1 AND t.black = 0 THEN 'yes' ELSE 'no' END AS redOnly

这是一个演示:

SQLFiddle