我有一张看起来像这样的表:
+-----------------+--------------+
| 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);
我认为错误:群组功能嵌套太深
答案 0 :(得分:1)
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 |
答案 1 :(得分: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