2015-11-08 101 views
0

我有一個表,看起來像這樣:組函數嵌套太深SQL錯誤

+-----------------+--------------+ 
| Field   | Type   | 
+-----------------+--------------+ 
| orderNumber (PK)| int   | 
| orderDate  | date   | 
| requiredDate | date   | 
| shippedDate  | date   | 
| status   | char(15)  | 
| comments  | char(200) | 
| customerNumber | int   | 
+-----------------+--------------+ 

我需要回到它有訂單的最大數量爲CustomerNumber。

我嘗試以下命令:

SELECT customerNumber FROM ORDERS WHERE customerNumber IN (SELECT customerNumber FROM ORDERS HAVING MAX(COUNT(customerNumber)) GROUP BY customerNumber); 

我認爲一個錯誤:組函數嵌套太深

回答

1

SQL Fiddle

的Oracle 11g R2架構設置

CREATE TABLE ORDERS (
    orderNumber  int PRIMARY KEY, 
    orderDate  date, 
    requiredDate date, 
    shippedDate  date, 
    status   char(15), 
    comments  char(200), 
    customerNumber int 
); 

INSERT INTO ORDERS (ORDERNUMBER, CUSTOMERNUMBER) VALUES (1, 1); 
INSERT INTO ORDERS (ORDERNUMBER, CUSTOMERNUMBER) VALUES (2, 1); 
INSERT INTO ORDERS (ORDERNUMBER, CUSTOMERNUMBER) VALUES (3, 2); 
INSERT INTO ORDERS (ORDERNUMBER, CUSTOMERNUMBER) VALUES (4, 2); 
INSERT INTO ORDERS (ORDERNUMBER, CUSTOMERNUMBER) VALUES (5, 3); 
INSERT INTO ORDERS (ORDERNUMBER, CUSTOMERNUMBER) VALUES (6, 4); 

查詢1 - 如果你只想得到一個單一的客戶

SELECT CUSTOMERNUMBER 
FROM (
    SELECT CUSTOMERNUMBER, 
     COUNT(ORDERNUMBER) AS num_orders 
    FROM ORDERS 
    GROUP BY CUSTOMERNUMBER 
    ORDER BY num_orders DESC 
) 
WHERE ROWNUM = 1 

Results

| CUSTOMERNUMBER | 
|----------------| 
|    1 | 

查詢2 - 如果你想獲得所有客戶的訂單數最高

SELECT CUSTOMERNUMBER 
FROM (
    SELECT CUSTOMERNUMBER, 
     RANK() OVER (ORDER BY NUM_ORDERS DESC) AS RNK 
    FROM (
    SELECT CUSTOMERNUMBER, 
      COUNT(ORDERNUMBER) AS num_orders 
    FROM ORDERS 
    GROUP BY CUSTOMERNUMBER 
    ORDER BY num_orders DESC 
) 
) 
WHERE RNK = 1 

Results

| CUSTOMERNUMBER | 
|----------------| 
|    1 | 
|    2 | 
+0

如果有多個等值的行,該怎麼辦? – user1692342

+0

@ user1692342該問題沒有指定需要多行 - 但是,我已經更新了第二個解決方案,該解決方案將返回訂單數量最高的多行(並且不需要任何自連接)。 – MT0

0

一種方法是使用cte S,你在哪裏得到訂單數在第一CTE,然後選擇最大值做。最後加入他們,以獲得最大訂單的客戶。

with ordercount as (select customernumber, count(distinct ordernumber) ordercount 
        from orders 
        group by customernumber) 
,maxorders as (select max(ordercount) maxcount from ordercount) 
select o.customernumber 
from ordercount o 
join maxorders m on m.maxcount = o.ordercount