【问题标题】:Get the row with the max value in sql [duplicate]获取sql中具有最大值的行[重复]
【发布时间】:2018-02-09 08:24:02
【问题描述】:

我想获取列上具有最大值的行。在我的情况下,我只想对具有 31 的 X 进行 ptint。这是我的代码,也是输出。

create temp view Private(marca) as
    Select a.marca, count(*) as totaleNoleggi, count(distinct a.targa) as totaleAuto, sum(extract(hour from (n.fine-n.inizio))) as totOre
    from auto a join noleggio n on a.targa=n.targa
    group by a.marca;

select marca, totOre
from Private 
group by marca,totore
order by totore desc
limit 1;

    marca   totalenoleggi   totaleauto  totore
1   Audi    1                  1          7
2   BMW     5                  4          7
3   VW      2                  1          1
4   X       2                  1          31

    marca   totore
1   X         31

但这是错误的方法,例如没有 X , Audi 或 BMW 有 7 但我的选择将只打印第一个 Audi。所以这是另一种获取最大值的方法

【问题讨论】:

标签: sql postgresql greatest-n-per-group postgresql-9.4


【解决方案1】:

我觉得ALL 构造在这里很有用

SELECT marca, totOre
FROM Private 
WHERE totore >= ALL(select totore from private)

【讨论】:

    【解决方案2】:

    你可以使用子查询

    select marca, totOre
    from Private 
    where totore = (select max(totore) from private)
    

    希望它会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      相关资源
      最近更新 更多