查找订单数量最多的客户:组函数嵌套太深错误

时间:2015-11-14 17:24:51

标签: sql database oracle

我需要找到订单数量最多的客户的名字。这是我的架构:

CREATE TABLE customers (
    cno NUMBER(6) NOT NULL,
    cname CHAR(30) NOT NULL,
    street VARCHAR(30) ,
    zip NUMBER,
    phone CHAR(12),
    FOREIGN KEY (zip) REFERENCES zipcodes (zip),
    PRIMARY KEY (cno)
);

CREATE TABLE orders (
    ono NUMBER(6) NOT NULL, 
    cno NUMBER NOT NULL,
    eno NUMBER NOT NULL,
    received DATE,
    shipped DATE,
    FOREIGN KEY (cno) REFERENCES customers (cno),
    FOREIGN KEY (eno) REFERENCES employee (eno), 
    PRIMARY KEY (ono)
);

以下是我根据这些规范返回客户名称的代码:

SELECT DISTINCT cname
FROM customers, orders
WHERE orders.cno = customers.cno
GROUP BY orders.cno
HAVING COUNT(orders.ono) >= MAX(COUNT(orders.ono));

使用此代码我将“组功能嵌套得太深”作为错误。关于我做错了什么以及如何解决这个问题的任何想法?

3 个答案:

答案 0 :(得分:1)

如果可能有多个订单数量最多的客户,则排名或密集排名功能最佳,例如。

SELECT cname
  FROM (SELECT cname
               rank() OVER (ORDER BY orders DESC) AS order_rank
          FROM (SELECT c.cname,
                       count(o.ono) AS orders
                  FROM customers c
                       LEFT JOIN orders o
                         ON o.cno = c.cno
              GROUP BY c.cname)
 WHERE order_rank = 1

答案 1 :(得分:0)

看起来您无法嵌套群组功能(例如MAXCOUNT),因此MAX(COUNT(orders.ono))将是非法的。您可以通过嵌套SELECT语句来解决问题,而无需嵌套函数调用:

WITH order_count AS  -- This query will do the aggregation and counting.
  SELECT cno, COUNT(cno) count
  FROM orders
  GROUP BY cno
SELECT customers.cname -- This query will find the customer with the highest count.
FROM customers
JOIN order_count ON customers.cno = order_count.cno
WHERE order_count.count = (SELECT MAX(count) FROM order_count)

或者你可以这样做:

SELECT cname FROM ( -- This query picks the top one.
  SELECT customers.cname, ROWNUM rn  -- This query lists the customers ordered by how many orders they have.
  FROM orders
  JOIN customers ON customers.cno = orders.cno
  GROUP BY cno
  ORDER BY COUNT(cno) DESC
) WHERE rn = 1;

答案 2 :(得分:0)

  

我需要找到订单数量最多的客户名称。

您提到复数形式的客户这一事实告诉我,您可能只对订单数量最多的客户感兴趣。您不清楚这一点,但如果您需要让我们说3个订单数量最多的客户,以下查询将会这样做:

with order_cnt_by_customer as (
  select o.cno, count(*) as order_cnt
    from orders o
   group by o.cno
)
select cname
  from (select c.cname,
               row_number() over (order by ocnt.order_cnt desc nulls last) as rn
          from customers c
          left join order_cnt_by_customer ocnt
            on ocnt.cno = c.cno)
 where rn <= 3 -- change this number to get N number of customers

如果您需要不同数量的客户,只需将最后一个条件更改为您需要的数字。