2017-05-18 146 views
-1

我使用子查詢得到了有關Oracle SQL的問題。關於子查詢條件的Oracle SQL

與表如下所示

enter image description here

問題是。

「編寫一個查詢,該查詢將顯示引用最大客戶數的客戶。」

你可以看到的基準最大號的客戶,當你執行這個代碼,

SELECT cust_referred, COUNT(*) 
FROM customer 
WHERE cust_referred IS NOT NULL 
GROUP BY cust_referred; 

我想我需要匹配CUST_NUM(上表)與參考的最大數量,以cust_referred這是1003 3.

+1

你有沒有試過自己? – KeithC

+0

搞錯了,我們不能看到我上傳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(*)) ); –

+0

請閱讀http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557和接受的答案 –

回答

0

如果我明白你正確的問題,我認爲這是你在找什麼

select cust_num, count(cust_refferred) from customer where cust_referred IS NOT NULL group by cust_num order by 2 desc

+0

我想你是說我可以選擇第一行或最後一行訂購後。但是,如果有多個最大數字,我不能選擇一個。 –

0

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) 
/