2015-03-31 57 views
0

我已經在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

你不能像這樣使用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 
1

使用Order BYROWNUM

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 
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;