gpt4 book ai didi

sql - 如何使空值在 SQL 中被视为 MAX?

转载 作者:行者123 更新时间:2023-11-29 12:29:57 24 4
gpt4 key购买 nike

为了能够说明情况,假设我有一张 table

Product price
Cola 2
Cola null
Fanta 1
Fanta 2
Sprite 2
Sprite null

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

非常感谢您的帮助!提前谢谢你。

最佳答案

标准 SQL 允许您使用 ORDER 中的表达式 NULLS FIRSTNULLS LAST 指定 NULL 值应该排序的位置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
;

对于 Postgres,使用 distinct on 通常会更快:

select distinct on (product) product, price
from products
order by product, price nulls first

关于sql - 如何使空值在 SQL 中被视为 MAX?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26949596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com