max(count)sql ......... join table或subquery

时间:2015-09-12 11:49:32

标签: sql count max ibm-db2

产品表

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个表组合成以产生输出...

客户名称|买单项次|最常见的产品类型

Kobe,3,Beverage

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;

我的尝试代码,但第3个1小时问题

1 个答案:

答案 0 :(得分:0)

使用group by连接三个表。试试这个

select Cust_name, sum( Sales_quantity) Bought , Product_name
from customer c inner join  Sales s on c.Cust_id=s.Cust_id
inner join Product p on s.Product_id=p.Product_id
group by c.Cust_name,p.Product_name

检查http://www.sqlfiddle.com/#!3/b835e/5