我有一个以下格式的示例表,其中包含示例数据:
= cust_table
Customer: Liked_Color:
Adam Blue
Adam Green
Adam Yellow
Adam Red
Bob Yellow
Bob Yellow
Bob Yellow
Bob Yellow
Charlie Red
Charlie Red
Charlie Red
Charlie Red
我该如何选择不同的客户,并且仅在不喜欢蓝色的情况下才返回他们?
因此,返回的结果将是:
客户:Bob,Charlie
如果我这样做:
SELECT DISTINCT Customer
FROM cust_table
WHERE Liked_Color NOT LIKE Blue
我明白了:亚当,鲍勃,查理
我如何确保仅当Blue不是客户的Liked_Color时才返回客户?
答案 0 :(得分:1)
我将使用聚合:
select customer
from cust_table
group by customer
having sum(case when color = 'Blue' then 1 else 0 end) = 0;
但是,customer
表中每个客户应该有一行(至少每单位时间)。如果您有这样一个表和一个customer_colors
表,那么我将使用not exists
:
select c.*
from customers c
where not exists (select 1
from customer_colors cc
where cc.customer = c.customer and cc.color = 'Blue'
);
这也将使返回的客户根本没有首选的颜色,而这是您无法用单个表完成的。
答案 1 :(得分:0)
或者,查看集合是否有好处:
SQL> with cust (customer, liked_color) as
2 (select 'Adam' , 'Blue' from dual union all
3 select 'Adam' , 'Green' from dual union all
4 select 'Bob' , 'Yellow' from dual union all
5 select 'Bob' , 'Red' from dual union all
6 select 'Charlie', 'Red' from dual union all
7 select 'Charlie', 'Red' from dual
8 )
9 select customer from cust where liked_color <> 'Blue'
10 minus
11 select customer from cust where liked_color = 'Blue';
CUSTOME
-------
Bob
Charlie
SQL>
答案 2 :(得分:0)
这将是所有方法中最简单的方法:
select distinct a from Table1 where a not in
(select distinct a from Table1 where b like 'Blue');