Sql 如何返回满足条件的不同行
我有以下格式的示例表和示例数据: =客户表Sql 如何返回满足条件的不同行,sql,oracle,Sql,Oracle,我有以下格式的示例表和示例数据: =客户表 Customer: Liked_Color: Adam Blue Adam Green Adam Yellow Adam Red Bob Yellow Bob Yellow Bob Yellow Bob Yellow Charlie Red Charlie Red
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
我如何选择不同的客户,并仅在他们不喜欢蓝色时才将其退回
因此,返回的结果将是:
顾客:鲍勃,查理
如果我这样做:
SELECT DISTINCT Customer
FROM cust_table
WHERE Liked_Color NOT LIKE Blue
我得到:亚当,鲍勃,查理
如何确保只有当蓝色不是客户喜欢的颜色时才返回客户?我会使用聚合:
select customer
from cust_table
group by customer
having sum(case when color = 'Blue' then 1 else 0 end) = 0;
但是,一个customer表至少在单位时间内每个customer应该有一行。如果您有这样一个表和一个customer_colors表,那么我将使用not exists:
这也会让客户返回完全没有首选颜色的产品,这是单张桌子无法做到的。或者,看看套装是否有任何好处:
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>
这将是其中最简单的一种:
select distinct a from Table1 where a not in
(select distinct a from Table1 where b like 'Blue');
检查小提琴:你为什么破坏了漂亮的格式?
select distinct a from Table1 where a not in
(select distinct a from Table1 where b like 'Blue');