cust_referred
是做過轉介的客戶。所以你想要的基本查詢是
SELECT cust_referred
, COUNT(*) as referrals
FROM customer
WHERE cust_referred IS NOT NULL
GROUP BY cust_referred
;
現在它成爲前n個問題。
「我不能只選擇一個,如果有一個以上的最大數量。」
在Oracle 12c中有奇妙的FETCH條款,這使得這個簡單:
SELECT cust_referred
, COUNT(*) as referrals
FROM customer
WHERE cust_referred IS NOT NULL
GROUP BY cust_referred
order by 2 desc
fetch first 1 rows with ties;
這個(狡猾的英語語法,但合法的Oracle 12c)將返回推薦人數最多的cust_refered
,或者如果有聯繫,則返回全部人數。
在早期的Oracle版本中有幾種不同的實現,但它們都比較笨拙。例如:
with cte as (
SELECT cust_referred
, COUNT(*) as referrals
FROM customer
WHERE cust_referred IS NOT NULL
GROUP BY cust_referred
)
select *
from cte
where cte.referrals = (select max(referrals) from cte)
/
來源
2017-05-19 10:47:09
APC
你有沒有試過自己? – KeithC
搞錯了,我們不能看到我上傳talbe .. 我試圖 SELECT CUST_NUM,cust_fname,cust_lname從客戶 GROUP BY CUST_NUM,cust_fname,cust_lname HAVING CUST_NUM =( SELECT cust_referred FROM (選擇cust_referred,COUNT (*)FROM customer WHERE cust_referred IS NOT NULL GROUP BY cust_referred) WHERE COUNT(*)= MAX(COUNT(*)) ); –
請閱讀http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557和接受的答案 –