访问SQL查询 - 仅在整个组中提取值时才提取值

时间:2016-02-13 17:10:08

标签: sql ms-access ms-access-2010

我尝试根据以下简单数据集在Access 2010中编写查询:

**Lot   Fruit**
1   Mango
1   Mango
1   Apple
1   Orange
2   Apple
2   Apple
2   Apple
3   Apple
3   Mango
4   Mango
4   Mango
4   Mango
5   Apple
5   Apple

我只想提取那些Lot no.,其中水果在每个Lot中只有一种类型。

例如,假设我想要获取Fruit = "Apple"的数据,那么它应该只提取Lot只有" Apple"同一批中没有其他水果。

在我们的示例中,如果我想要所有只有Apple的批次,那么查询应该带来以下结果。

Lot Fruit
2   Apple
2   Apple
2   Apple
5   Apple
5   Apple

我尝试了各种SQL查询,但没有运气,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT Lot
FROM mytable
GROUP BY Lot
HAVING COUNT(CASE WHEN Fruit <> 'Apple' THEN 1 END) = 0

或者尝试:

SELECT DISTINCT Lot
FROM mytable AS t1    
WHERE Fruit = 'Apple' AND 
      NOT EXISTS (SELECT 1
                  FROM mytable AS t2
                  WHERE t1.Lot = t2.Lot AND t2.Fruit <> 'Apple')

也可以使用LEFT JOIN

SELECT DISTINCT Lot
FROM mytable AS t1
LEFT JOIN mytable AS t2 ON t1.Lot = t2.Lot AND t2.Fruit <> 'Apple'
WHERE t1.Fruit = 'Apple' AND t2.Lot IS NULL