0

我尝试使用 DISTINCT ON 和 posrgresql 来实现以下目标:假设我有一个如下所示的表:

id  time   price
1   12:00  10
1   13:00  20
1   14:00  30

我的目标是创建一个每个 id 仅包含 1 行的表,其中显示最小时间价格和最大时间价格的列。看起来像这样的东西:

id  min_time_price  max_time_price
1   10              30

我尝试使用 DISTINCT ON (id) 但无法真正得到它。

希望得到一些帮助,谢谢!

4

1 回答 1

0

这是一种方法:

select t.id, tmin.price, tmax.price
from (select t.id, min(time) as min_time, max(time) as max_time
      from t
     ) t join
     t tmin
     on t.id = tmin.id and t.min_time = tmin.time join
     t tmax
     on t.id = tmax.id and t.max_time = tmax.time;

您还可以使用聚合。Postgres 没有first()/last()聚合函数,但是数组很方便:

select t.id,
       array_agg(price order by time asc)[1] as min_time_price,
       array_agg(price order by time desc)[1] as max_time_price
from t
group by id;

或使用first_value()and last_value()

select distinct t.id,
       first_value(price) over (partition by time order by time) as min_time_price,
       first_value(price) over (partition by time order by time desc) as max_time_price
from t
于 2019-10-30T14:53:44.770 回答