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

t3irkdon  于 2021-06-20  发布在  Mysql
关注(0)|答案(5)|浏览(248)
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)

被退回

x9ybnkn6

x9ybnkn61#

这里有一种方法 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) 而是排除那些记录。不清楚你的张贴,如果这是重要的或没有。

polhcujo

polhcujo2#

我会用 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')
                 );
g6ll5ycj

g6ll5ycj3#

您可以尝试此查询:

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

gupuwyp24#

返回人员 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')
jutyujz0

jutyujz05#

我会这样写:

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;

相关问题