我需要选择一个列表,显示雇用汽车的每个客户的客户ID,职位,名字和姓氏,按客户姓名的字母顺序排序,以及每个客户已经预订的数量。< / p>
我已完成第一部分,但不确定在何处计算预订数量。
以下表格是
create table customer
(customer_id char(4) primary key not null,
customer_sname varchar (30) not null,
customer_fname varchar (30) not null,
customer_title varchar (6) not null,
customer_address1 varchar (35) not null,
customer_address2 varchar (35) null,
customer_postcode varchar (25) null,
customer_phone varchar (30) null,
customer_email varchar (40) null,
customer_di varchar (40) not null)
ENGINE=InnoDB;
create table car_booking
(booking_id INTEGER AUTO_INCREMENT primary key not null,
car_id char (4) not null,
customer_id char (4) not null,
hire_sdate date not null,
hire_edate date not null)
engine=innodb
我已经完成了这个
select customer_id, customer_title, Customer_fname, customer_sname
from customer
where customer_id in
(select customer_id from car_booking )
order by customer_sname asc
由于
答案 0 :(得分:1)
这将需要使用聚合函数(COUNT),GROUP BY子句和LEFT JOIN到CAR_BOOKING表:
SELECT c.customer_id, c.customer_title, c.customer_fname, c.customer_sname,
COALESCE(COUNT(*), 0) AS num_bookings
FROM CUSTOMER c
LEFT JOIN CAR_BOOKING cb ON cb.customer_id = c.customer_id
GROUP BY c.customer_id, c.customer_title, c.customer_fname, c.customer_sname
ORDER BY c.customer_sname
因为有些列没有包含在像COUNT这样的聚合函数中,所以需要在GROUP BY子句中定义这些列。
我使用LEFT OUTER JOIN到CAR_BOOKINGS
表来返回没有预订的客户 - 这些记录将在num_booking
列中显示为零。您可以在查询中省略LEFT
关键字,仅返回客户&amp;计入预订。 COALESCE是一个将空值转换为所需值的标准函数 - 在这种情况下,计数为空...
答案 1 :(得分:0)
在SQL Server中,我使用:
select c.customer_id,
c.customer_title,
c.customer_fname,
c.customer_sname,
count (*)
from cutomer c,
car_booking cb
where cb.customer_id = c.customer_id
group by c.customer_id,
c.customer_title,
c.customer_fname,
c.customer_sname
不熟悉MySQL,所以它可能会有所不同,但这是一般的想法。
答案 2 :(得分:0)
select customer.customer_id, customer.customer_title, customer.customer_fname, customer.customer_sname, count(*) as Bookings
from customer JOIN car_booking ON customer.customer_id = car_booking.customer_id
GROUP BY customer.customer_id, customer.customer_title, customer.Customer_fname, customer.customer_sname
order by customer_sname asc