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

时间:2014-11-15 19:06:20

标签: sql postgresql max

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

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

我需要编写一个返回每个产品最高价格的查询,如果价格为空,则将其视为最大值。 所以对于这个表,它应该返回Cola null,Fanta 2,Sprite null。

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

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

标准SQL允许您使用NULL语句中的表达式NULLS FIRSTNULLS LAST指定应对ORDER 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

答案 2 :(得分:0)

我决定采用以下方法。当然,您需要确定价格列的“类型”,并使列的最大值等于所使用的DBMS中的最大值。

SELECT product, NULLIF(MAX(COALESCE(price, 2147483647)),2147483647) as max_price
FROM product_pricing
GROUP BY product

答案 3 :(得分:0)

您也可以尝试以下方法:

select product, 
    case when (count(*) - count(price)) > 0 then null else max(price) end as max_price
from t
group by product

这里是小提琴:http://sqlfiddle.com/#!17/ea15b/1/0

答案 4 :(得分:-1)

create table #test(
prod varchar(10),
qty int
)

insert #test(prod, qty)
values ('Cola', 2), ('Cola', NULL), ('Fanta', 1), ('Fanta', 2)

select case when max(s.qty) = 9999999 then NULL else max(s.qty) end, 
    s.prod
from (select coalesce(qty, 9999999) as qty, prod from #test) s
group by prod