我正在使用Oracle SQL广告编写一个查询,该查询将显示引用了最大客户数量的客户详细信息。可以有一个以上的客户(如果每个客户的推荐人数上限相同)。
在包含CUSTOMER
的{{1}}表中,我可以使用以下命令获取CUS_ID, CUS_NAME, CUS_REFERRED
和CUS_REFERRED
:
COUNT(CUST_REFERRED)
样本数据:
select CUST_REFERRED, count(CUST_REFERRED)
from CUSTOMER
group by CUST_REFERRED
having count(CUST_REFERRED) = (select max(MYCOUNT)
from (select cust_referred,
count(CUST_REFERRED) MYCOUNT
from CUSTOMER
group by CUST_REFERRED));
当前输出:
Cust_Num Cust_FName Cust_Referred
------------------------------------------------
1000 Patricia (null)
1001 Jim 1000
1002 Zoe 1003
1003 John (null)
1004 Marie 1003
1005 Anthony 1002
1006 Jodee 1003
所需的输出:
CUST_REFERRED COUNT(C.CUST_REFERRED)
------------- ----------------------
1003 3
John是客户1003的地方,其推荐人数最多(3)。如果另一个人(例如杰克)也进行了3次推荐,那么他也会被列出。
但是,每当我尝试添加CUST_FNAME CUST_REFERRED COUNT(C.CUST_REFERRED)
---------- ------------- ----------------------
John 1003 3
时,都会得到“没有返回行”(如果在主选择查询中)或具有1个引荐的客户列表(在嵌套的选择查询中)。
任何帮助,不胜感激!
答案 0 :(得分:1)
使用窗口功能:
select cust_referred, cnt
from (select cust_referred, count(*) as cnt,
rank() over (order by count(*)) as seqnum
from customer
group by cust_referred
) c
where seqnum = 1;
如果您需要有关客户的更多信息,则可以将其重新加入到customer
表中。
答案 1 :(得分:0)
从Oracle 12c开始:
[(55.548745, 35.547852), (57.85425, 37.524852), (57.214445, 38.587852)]
在旧版本中:
select c.cust_num, c.cust_fname, cr.cnt
from customer c
join
(
select cust_referred, count(*) as cnt
from customer
group by cust_referred
order by count(*) desc
fetch first row with ties
) cr on cr.cust_referred = c.cust_num;
演示:https://dbfiddle.uk/?rdbms=oracle_18&fiddle=aa5875f649943cacaa3e03b86ebe3cf4