返回仅拥有汽车,摩托车或汽车和摩托车的人的列表

时间:2018-06-21 17:36:31

标签: mysql sql

Table 1

Name, Vehicle
P1, Car
P1, Motorcylce
P1, Truck
P1, Helicopter
P2, Car
P3, Motorcycle
P4, Motorcycle
P4, Car
P5, Car
P5, Truck
P6, Motorcycle
P6, Truck
P7 Truck

如何查询上表,以便只有拥有汽车或摩托车或必须同时拥有汽车和摩托车的人返回。

所以

P2 -> only has a car (valid)
P3 -> only has a motorcyle (valid)
P4 -> has both car and motorcycle (valid)

已退回

5 个答案:

答案 0 :(得分:2)

这是使用conditional aggregation的一种方法:

select name
from yourtable
group by name
having count(case when vehicle = 'Car' then 1
                  when vehicle = 'Motorcycle' then 1
             end) = count(*)

如果您不希望自己返回的人有多于一辆汽车或摩托车(例如,P8有2辆汽车),请使用count(distinct vehicle)来排除这些记录。不清楚是否重要。

答案 1 :(得分:0)

您可以尝试以下查询:

select Name from table 
where Name  not in (select distinct Name from table where Vehicle in 
('Helicopter','Truck'))

答案 2 :(得分:0)

EXCEPT归还那些非汽车或摩托车的人。

select name from tablename
except
select name from tablename where vehicle not in ('Car', 'Motorcycle')

额外的WHERE子句可以加快速度:

select name from tablename where vehicle in ('Car', 'Motorcycle')
except
select name from tablename where vehicle not in ('Car', 'Motorcycle')

答案 3 :(得分:0)

我会这样写:

select name
from yourtable
where vehicle in ('car', 'motorbike')
group by name
having count(*) = 2;

这假定每种类型只有一行。如果没有,请使用count(distinct)

select name
from yourtable
where vehicle in ('car', 'motorbike')
group by name
having count(distinct vehicle) = 2;

答案 4 :(得分:0)

我会使用NOT EXISTS

select t.*
from table t
where not exists (select 1 
                  from table t1 
                  where t1.name = t.name and 
                        t1.Vehicle in ('Helicopter', 'Truck')
                 );