一张桌子的交叉点

时间:2017-01-16 09:04:34

标签: sql intersection

我想得到一张桌子的交集。 我的表格列出了几个市场中出现的产品。我如何获得位置A和B的产品(例如这个苹果)?

product     market
apple       location A
apple       location B
orange      location C

2 个答案:

答案 0 :(得分:1)

这是一个选项:

SELECT product
FROM yourTable
WHERE market IN ('location A', 'location B')
GROUP BY product
HAVING COUNT(DISTINCT market) = 2

另一种可能性是使用条件聚合并计算给定市场与每种产品一起出现的次数:

SELECT product
FROM yourTable
GROUP BY product
HAVING SUM(CASE WHEN market = 'location A' THEN 1 ELSE 0 END) > 0 AND    -- appears in A
       SUM(CASE WHEN market = 'location B' THEN 1 ELSE 0 END) > 0        -- appears in B

答案 1 :(得分:0)

你可以通过“内部加入”来实现这一目标。如下

select t.product
from product t
inner join 
      (select product from product where market = 'location A') tt on t.product = tt.product
where market = 'location B'