我需要查询以下语句:
显示为客户预订超过4辆汽车租赁的所有员工的详细信息。
架构如下:
Staff (staffID, firstname, lastname, xyz..)
Customers (customerID, firstname, lastname, xyz..)
Booking (bookingID, staffID, customerID, vehicleregistration, date)
Vehicle (vehicleregistration, make, model, xyz..)
干杯!
答案 0 :(得分:2)
我认为所有预订记录是客户的实际车辆租赁。所以你想要计算每个员工。 每位员工转换为GROUP BY staffid
。要检查汇总结果(计数),请使用HAVING
子句。
select *
from staff
where staffid in
(
select staffid
from booking
group by staffid
having count(*) > 4
);
如您所见,无需加入任何内容,因为您只需要员工表中的数据。预订计数是最好属于WHERE
条款的标准。
为了完整起见,这里有一个连接:
select s.*
from staff s
join
(
select staffid
from booking
group by staffid
having count(*) > 4
) b on b.staffid = s.staffid;
我发现这种可读性较差,但有些人可能更喜欢它。如果您希望在结果中显示聚合中的信息,则可以使用此选项,在您的情况下是计数。
select s.*, b.bookings
from staff s
join
(
select staffid, count(*) as bookings
from booking
group by staffid
having count(*) > 4
) b on b.staffid = s.staffid;
答案 1 :(得分:0)
SELECT staffID,COUNT(vehicleregistration) FROM Staff JOIN Booking ON Staff.staffID = Booking.staffID JOIN Vehicle ON Vehicle.vehicleregistration = Booking.vehicleregistration GROUP BY staffID HAVING COUNT(vehicleregistration) > 4