我有一张卡车和位置的桌子,每辆卡车每个位置都有很多记录: 例如:
truck | location
----------------
60111 | 1
60111 | 2
60111 | 3
60111 | 4
60222 | 1
60222 | 2
....等
我想选择(1,2)中只有位置的卡车。 在我的例子中,返回必须是60222
怎么做? 注意:我想要一个没有硬编码的动态解决方案。
答案 0 :(得分:3)
类似于Patrick Hofman的解决方案是移动HAVING
子句中的逻辑
SELECT truck
FROM table
GROUP BY truck
HAVING COUNT(DISTINCT location) = 2
AND SUM(CASE WHEN location IN (1, 2) THEN 0 ELSE 1 END) = 0
第一个条件返回卡车只有两个不同的位置,没有检查它们的值,第二个条件强制那些位置是1和2
答案 1 :(得分:2)
这将选择完全位置1和2的卡车:
select t1.truck
from truck_location t1
where t1.location in (1, 2)
group by truck
having count(distinct t1.location) = 2
and count(distinct t1.location) = (select count(*)
from truck_location t2
where t2.truck = t1.truck);
只有将卡车分配到同一位置两次,才需要distinct
内的count()
。如果保证组合卡车/位置是唯一的,则无需这样做。
SQLFiddle:http://sqlfiddle.com/#!15/b865f/1
答案 2 :(得分:1)
select distinct truck
from
my_table
where
truck not in
(
select distinct truck
from my_table
where location not in (1, 2)
)
答案 3 :(得分:-2)
您可以通过卡车分组,过滤位置并检查结果是否为2:
select truck
from table
where location in (1, 2)
group
by truck
having count(distinct location) = 2