选择订单中具有最多不同类别的客户

时间:2016-01-28 13:24:21

标签: sql oracle

我需要回答的问题如下:找到客户(或者是平局的客户),他们已经完成了包含最多不同类别的订单。

这些是我的表格:

产品:

CREATE TABLE Products (
PROD_ID NUMBER NOT NULL ,
"CATEGORY" NUMBER NOT NULL REFERENCES Categories,
TITLE VARCHAR (40) NOT NULL,
ACTOR VARCHAR (40) NOT NULL,
PRICE VARCHAR (40) NOT NULL,
PRIMARY KEY (PROD_ID));

OrderLines:

CREATE TABLE Orderlines (
ORDERLINEID NUMBER NOT NULL,
ORDERID NUMBER NOT NULL REFERENCES Orders,
PROD_ID NUMBER NOT NULL REFERENCES Products,
QUANTITY NUMBER NOT NULL,
ORDERDATE VARCHAR2 (80) NOT NULL,
PRIMARY KEY (ORDERLINEID,ORDERID));

客户:

CREATE TABLE Customers (
CUSTOMERID NUMBER NOT NULL,
FIRSTNAME VARCHAR2 (20) NOT NULL,
LASTNAME VARCHAR2 (20) NOT NULL,
ADDRESS1 VARCHAR2 (40) NOT NULL,
ADDRESS2 VARCHAR2 (40),
CITY VARCHAR2 (20) NOT NULL,
STATE VARCHAR2 (20) NOT NULL,
ZIP VARCHAR2 (20) NOT NULL,
COUNTRY VARCHAR2 (20) NOT NULL,
REGION VARCHAR2 (20) NOT NULL,
EMAIL VARCHAR2 (20) NOT NULL,
PHONE VARCHAR2 (20) NOT NULL,
CREDITCARDTYPE VARCHAR2 (20) NOT NULL,
CREDITCARD VARCHAR2 (20) NOT NULL,
CREDITCARDEXPIRATION VARCHAR (10) NOT NULL,
USERNAME VARCHAR2 (20) NOT NULL,
"PASSWORD" VARCHAR2 (20) NOT NULL,
AGE NUMBER NOT NULL,
INCOME NUMBER NOT NULL,
GENDER VARCHAR2 (8) NOT NULL,
PRIMARY KEY (CUSTOMERID));

订单:

CREATE TABLE Orders (
ORDERID NUMBER NOT NULL,
ORDERDATE DATE NOT NULL,
CUSTOMERID NUMBER NOT NULL REFERENCES Customers,
NETAMOUNT NUMBER NOT NULL,
TAX NUMBER NOT NULL,
TOTALAMOUNT NUMBER NOT NULL,
PRIMARY KEY (ORDERID));

1 个答案:

答案 0 :(得分:0)

尝试:

Select * from
(
Select C.CUSTOMERID, C.FIRSTNAME , C.LASTNAME, count(distinct P."CATEGORY") as Categories
from Customers C
inner join Orders O on O.CUSTOMERID =C.CUSTOMERID
inner join OrderLines OL on O.ORDERID =OL.ORDERID 
inner join Products P on P.PROD_ID =OL.PROD_ID 
group by C.CUSTOMERID, C.FIRSTNAME , C.LASTNAME
Order by count(P."CATEGORY") desc)A
WHERE rownum = 1;