SQL获取列值等于最大值的行

时间:2017-12-02 21:31:30

标签: sql postgresql max

我使用查询select count(category), name from product natural join supplier group by name;得到了下表:

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

现在我想只获取count等于count列上最大值的行(在本例中为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;

在单个查询中有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:0)

您可以使用rank() over (order by count(*) desc)按计数排名,然后只保留排名第1的项目:

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

答案 1 :(得分: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;