产品表
CREATE TABLE product(
Product_id varchar(7) NOT NULL PRIMARY KEY,
Product_name varchar(40),
Product_type varchar(10)
);
INSERT INTO Product VALUES
('P001','Apple Cinnamon Cereal','Cereal'),
('P002','Chocolate Almond Cereal','Cereal'),
('P003','Chocolate Delight Cereal','Cereal'),
('P004','Chocolate Mocha Protein Shake','Beverage'),
('P005','Vanilla Cappuccino Protein Shake','Beverage'),
('P006','Multi-grain Crackers','Cracker'),
('P007','Chili Lime Cracker Chips ','Cracker');
销售表
CREATE TABLE Sales(
Time_id varchar(6) NOT NULL ,
Product_id varchar(7) NOT NULL,
Saler_id varchar(10) not null,
Cust_id varchar(10) NOT NULL,
Sales_quantity int,
Cost_sales decimal(5,2),
Primary key(Time_id,Product_id,Cust_id,Saler_id),
Foreign key (Time_id) references Time,
Foreign key (Product_id) references Product,
Foreign key (Saler_id) references Wholesaler,
Foreign key (Cust_id) references Customer);
insert into Sales values
('T001','P001','W002','C001',3,9.50),
('T003','P003','W005','C002',2,8.50),
('T004','P002','W001','C003',4,9.60),
('T005','P001','W004','C004',3,8.90),
('T003','P004','W001','C003',3,8.50),
('T002','P004','W001','C003',4,9.50)
客户表
CREATE TABLE customer(
Cust_idvarchar(10) NOT NULL PRIMARY KEY,
Cust_namevarchar(20),
Cust_gendervarchar(6),
Cust_DOB date,
Cust_addressvarchar(100)
)
INSERT INTO customer values
('C001','David Tan','Female','1992-06-18','Cyberia A2-4-5, PSN Multimedia, 63000 Cyberjaya, Selangor'),
('C002','Ariel Lin','Female','1987-07-23','Cyberia E-33-5, PSN Multimedia, 63000 Cyberjaya, Selangor'),
('C003','Kobe','Male','1992-06-18','Cyberia A2-4-5, PSN Multimedia, 63000 Cyberjaya, Selangor'),
('C004','Kelvin Tan','Male','1989-03-01','Cyberia B3-4-5, PSN Multimedia, 63000 Cyberjaya, Selangor'),
如何使用连接或子查询组合这 3 个表以产生如下输出...
客户姓名 | 购买物品次数 | 最常见的产品类型
科比 ,3 ,饮料
select customer.cust_name,count(sales.cust_id),max(product.product_type) from
(Sales
Inner join customer
On Customer.cust_id=Sales.cust_id
Inner join product
On Product.product_id=Sales.product_id)
Group by cust_name;
我的尝试代码,但 3rd 1 hv 问题