gpt4 book ai didi

sql - 使用 postgresql 按语句在组中选择特定值

转载 作者:行者123 更新时间:2023-11-29 14:36:19 25 4
gpt4 key购买 nike

比如我有这张表

价格

    price   |   location
------------+-------------
2.50 | U express
2.19 | Carrefour

如果我要求

SELECT avg(price), min(price), max(price) FROM prices GROUP BY price;

我会得到

  avg   |  min  |  max  
--------+-------+-------
2.34500 | 2.19 | 2.50

是否可以只使用一条sql语句得到如下结果?

  avg   |  min  |  max  |  minLocation  | maxLocation
--------+-------+-------+---------------+-------------
2.34500 | 2.19 | 2.50 | Carrefour | U express

minLocation 是价格最低的“位置”列中的值。以及价格最高的 ma​​xLocation

最佳答案

有多种方式。一种方法是使用子查询:

select avg(price), min(price), max(price),
max(case when seqnum_a = 1 then location end) as min_location,
max(case when seqnum_d = 1 then location end) as max_location
from (select p.*, row_number() over (order by price desc) as seqnum_d,
row_number() over (order by price asc) as seqnum_a
from prices p
) p;

这只是一种解决方案。 Postgres 提供数组、丰富的窗口函数和 filter 子句(速度稍快),它们也提供其他解决方案。以上是标准SQL,合理。

关于sql - 使用 postgresql 按语句在组中选择特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44134091/

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