选择具有相同名称的记录和具有两个值的另一个字段

时间:2016-02-24 01:50:36

标签: sql group-by

给出一个有不同颜色的产品表,

NAME  COLOR
----  -----
pen   red
pen   blue
pen   yellow
box   red
mic   red
tape  blue

如何找到redbluepen)中可用产品的名称,以及red中可用产品的名称,但是不在blueboxmic)?

小提琴:http://sqlfiddle.com/#!9/021a6/3

1 个答案:

答案 0 :(得分:2)

对于这些类型的查询,我喜欢group by having

两种颜色:

select name
from t
group by name
having sum(case when color = 'red' then 1 else 0 end) > 0 and
       sum(case when color = 'blue' then 1 else 0 end) > 0;

红色但不是蓝色:

select name
from t
group by name
having sum(case when color = 'red' then 1 else 0 end) > 0 and
       sum(case when color = 'blue' then 1 else 0 end) = 0;

having子句中的条件计算与条件匹配的行数(对于每个name)。因此,> 0表示至少有一行匹配,= 0表示没有匹配的行。

相关问题