我在sql开发人员中使用了两个表,以确定哪个客户已经下了最多的订单,直到找出每个客户下达的订单总数,但无法弄清楚如何只展示一个最多订单数量......
例如 - 这将为我提供所有下订单的客户和每个订单的订单数量列表
SELECT
customer.cust_num, customer.cust_bizname,
COUNT(invoice.inv_num) AS "TOTAL ORDERS"
FROM customer INNER JOIN invoice ON customer.cust_num = invoice.cust_num
GROUP BY customer.cust_num, customer.cust_bizname;
如果我尝试使用max和count ...
SELECT
customer.cust_num, customer.cust_bizname,
MAX(COUNT(invoice.inv_num)) AS "TOTAL ORDERS"
FROM customer INNER JOIN invoice ON customer.cust_num = invoice.cust_num
GROUP BY customer.cust_num, customer.cust_bizname;
我收到一条错误,指出“不是单组群组功能”。 如何有效地计算订单数量并仅显示订单数量最多的客户?
答案 0 :(得分:1)
将Order BY
与ROWNUM
select *
from
(SELECT customer.cust_num,
customer.cust_bizname,
COUNT(invoice.inv_num) AS "TOTAL ORDERS"
FROM customer
INNER JOIN invoice
ON customer.cust_num = invoice.cust_num
GROUP BY customer.cust_num, customer.cust_bizname
Order by "TOTAL ORDERS" DESC
)
Where ROWNUM =1
或使用Row_Number()
分析函数
select customer.cust_num,
customer.cust_bizname,
"TOTAL ORDERS"
FROM
(
SELECT Row_number() over(order by COUNT(invoice.inv_num) DESC) As RN
customer.cust_num,
customer.cust_bizname,
COUNT(invoice.inv_num) AS "TOTAL ORDERS"
FROM customer
INNER JOIN invoice
ON customer.cust_num = invoice.cust_num
GROUP BY customer.cust_num, customer.cust_bizname
)
Where RN=1
答案 1 :(得分:0)
你不能那样使用max
。相反,按降序排序并获得第一条记录,如下所示:
SELECT * FROM
(select customer.cust_num, customer.cust_bizname,
COUNT(invoice.inv_num) AS "TOTAL ORDERS"
FROM customer INNER JOIN invoice ON customer.cust_num = invoice.cust_num
GROUP BY customer.cust_num, customer.cust_bizname
ORDER BY "TOTAL ORDERS" desc)
WHERE rownum = 1
答案 2 :(得分:0)
在Oracle 12中,您可以使用ANSI标准fetch first 1 row only
:
SELECT c.cust_num, c.cust_bizname, COUNT(i.inv_num) AS "TOTAL ORDERS"
FROM customer c INNER JOIN
invoice i
ON c.cust_num = i.cust_num
GROUP BY c.cust_num, c.cust_bizname
ORDER BY COUNT(i.inv_num) DESC
FETCH FIRST 1 ROW ONLY;