如何在 SQL 中将空值视为 MAX?

Kab*_*hok 4 sql postgresql max

为了能够解释这种情况,假设我有一张桌子

Product price
Cola    2
Cola    null
Fanta    1
Fanta    2
Sprite   2
Sprite null
Run Code Online (Sandbox Code Playgroud)

我需要编写一个查询来返回每个产品的最高价格,如果价格为空,则将其视为最高价格。所以对于这个表,它应该返回可乐空、芬达 2、雪碧空。

我真的很感谢你的帮助!先感谢您。

jue*_*n d 6

select product, case when sum(case when price is null then 1 else 0 end) > 0
                     then null
                     else max(price)
                end as price
from your_table
group by product
Run Code Online (Sandbox Code Playgroud)


a_h*_*ame 5

标准 SQL 允许您NULL使用表达式NULLS FIRSTNULLS LASTORDER BY语句中指定值的排序位置。这可以与窗口函数结合使用以获得所需的行为:

select product, price
from (
   select product,
          price,
          row_number() over (partition by product order by price desc nulls first) as rn
   from products
) t
where rn = 1
order by product, price desc nulls first
;
Run Code Online (Sandbox Code Playgroud)

使用 Postgres 通常更快地distinct on用于此类查询:

select distinct on (product) product, price
from products
order by product, price nulls first
Run Code Online (Sandbox Code Playgroud)

  • +1 。。。“distinct on”方法特别适合 Postgres。 (2认同)