[英]SQL Oracle Find who has the max : having count(*) >= all(..) VS having count(*) = (select max(count(*))
我必須找出在桌子上最多的人。 我有兩種可行的解決方案,但我不知道它們之間是否有任何區別,以及更喜歡哪一種。
解決方案1:使用所有
select numPerson
From nameTable
Group by numPerson
Having count(*)>= all(select count(*) from nameTable group by numPerson);
解決方案2:使用最大值
select numPerson
From nameTable
Group by numPerson
Having count(*)= (select max(count(*)) from nameTable group by numPerson);
使用 window 函數有更好的方法來編寫它。 我不喜歡第二種語法嵌套聚合函數,因為它使用定制的 Oracle 功能——但 Oracle 的愛好者可能會喜歡它。 我會這樣寫:
having count(*)= (select max(cnt) from (select count(*) as cnt from nameTable group by numPerson) p);
但這與您的問題無關。 在你的having
條款中,兩者是等價的。
但是,有一些區別:
第一個涉及在子查詢中不返回任何行:
all
表單將返回所有行。 第二個涉及all
使用的列中的null
值:
all
不返回任何行。NULL
值,則聚合將忽略NULL
值。 由於查詢的性質,“子查詢不返回值時的所有行”與“無行”相同。 並且count(*)
永遠不會返回NULL
。 所以兩者是等價的。
select stats_mode(numperson) from nametable
以上將只返回一行。 如果出現平局,您的解決方案將返回多行。 如果您接受 Oracle window 函數,您可以獲得聯系但避免第二次“全表掃描”:
select numPerson from (
select numPerson, count(*) cnt, max(count(*)) over() max_cnt
from nameTable
group by numPerson
)
where cnt = max_cnt;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.