你怎么能在SQL中选择具有较高值的​​行呢?

How can you choose the line with the higher value in SQL?

假设我们有这个 table:

----------
number |name| price
----------
1     |  a |  2
----------
1     |  b |  4
----------
2     |  c |  4
----------
3     |  d |  6
----------

我要选择号码和他们的最高价。那么我如何才能 select 只显示价格较高的编号为 1 的行而不显示另一行呢?。我的问题是第二列。

简单:按

分组
select number, max(price)
from your_table
group by number;

如果您有更多列并且想要 select 具有最高价格的行,请使用:

select *
from (select
    t.*,
    row_number() over (partition by number order by price desc) rn
from your_table t) t
where rn = 1;

在 Postgres 中,为每个 number 获取具有最高 price 的行的最有效方法是使用 distinct on:

select distinct on (number) t.*
from t
order by number, price desc;