如何获得客户数量?

时间:2018-05-25 16:19:41

标签: sql postgresql


我需要一些SQL查询的帮助 假设我们有一个管理酒店预订的示例数据库:

Customer(ID, name, birthDate, city);
Room(number, floor, beds, roomtype, price);
Bookings(Customer, roomNumber, floor, checkInDate, checkOutDate);

我需要知道哪些客户只预订了,而且只有经济型客房。 这是我的问题:

select Customer from Bookings
   join Room on(Bookings.num = camera.roomNumber and Bookings.floor= 
   Room.floor)
        where (Bookings.Customer, Bookings.floor) not in (select number, floor from 
        Room where roomType != 'economic')

我的问题是,此查询向我显示预订经济房间的客户,但它也向我显示预订其他类型房间的客户。 如何限制输出以获得仅预订经济房间的客户? 谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用聚合:

select b.Customer
from Bookings b join
     Room r
     on b.num = r.roomNumber and b.floor = r.floor
group by b.Customer
having min(roomType) = max(roomType) and min(roomType) = 'economic';

答案 1 :(得分:2)

使用not exists

select c.*
from Customer c
where not exists (select 1 
                  from Bookings b
                  inner join Room r on b.num = r.roomNumber and b.floor = r.floor
                  where c.ID = b.Customer and r.roomType <> 'economic'
                  );