Get values from first and last row per group

前端 未结 2 2013
花落未央
花落未央 2020-12-03 15:05

I\'m new to Postgres, coming from MySQL and hoping that one of y\'all would be able to help me out.

I have a table with three columns: name, week

2条回答
  •  抹茶落季
    2020-12-03 15:46

    This is a bit of a pain, because Postgres has the nice window functions first_value() and last_value(), but these are not aggregation functions. So, here is one way:

    select t.name, min(t.week) as minWeek, max(firstvalue) as firstvalue,
           max(t.week) as maxWeek, max(lastvalue) as lastValue
    from (select t.*, first_value(value) over (partition by name order by week) as firstvalue,
                 last_value(value) over (partition by name order by week) as lastvalue
          from table t
         ) t
    group by t.name;
    

提交回复
热议问题