2017-12-02 178 views
1

我下表得到了與查詢select count(category), name from product natural join supplier group by name;SQL取得與列值的行等於最大值

count | nome  
-------+----------- 
    1 | CandyCorp 
    1 | Nike 
    1 | DrinksInc 
    7 | Mutante 
    1 | Colt 
    7 | Mazzetti 

現在我想獲取僅相當於在數列中的最大值在與數列(在這種情況下7),得到:

count | nome  
-------+----------- 
    7 | Mutant 
    7 | Mazzetti 

編輯:我得到了它通過創建臨時表工作:

create table auxtable as (select count(categoria),name from product natural join supplier group by name); 

select name from auxtable a1 join (select max(count) as countMax from auxtable) a2 on a1.count=a2.countMax; 

drop table auxtable; 

在單個查詢中有沒有辦法解決這個問題?

回答

0

,你可以用它代替臨時表CTE:

with auxtable as (select count(categoria),name from product natural join supplier group by name) 
select name from auxtable a1 
join (select max(count) as countMax from auxtable) a2 on a1.count=a2.countMax; 
0

可以使用rank() over (order by count(*) desc)通過數排名,然後就保持排名第一的項目:

select * from (
    select 
     rank() over (order by count(category) desc) rn, 
     name, count(category) 
    from product natural join supplier 
    group by name 
) t where rn = 1 

http://sqlfiddle.com/#!15/26b68/1

+0

謝謝你爲你的答案,但是,因爲這是一項任務,我不允許使用rank()。 –