【问题标题】:DISTINCT ON to find min and max timesDISTINCT ON 查找最小和最大时间
【发布时间】:2019-10-30 14:50:26
【问题描述】:

我已经尝试使用 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) 但无法真正得到它。

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

【问题讨论】:

    标签: sql postgresql distinct-on


    【解决方案1】:

    这是一种方法:

    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()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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2015-03-28
      • 2010-12-26
      • 1970-01-01
      • 2012-09-05
      • 2012-09-16
      • 1970-01-01
      相关资源
      最近更新 更多