我从非常复杂的查询中获取此表,也就是说,它无法自行加入。 行按时间排序。
type, value, time
+---+----+
| 2 | 2 |
| 2 | 7 |
| 3 | 20 |
| 3 | 16 |
+---+----+
我需要计算每个类型分组的第一个值和最后一个值之间的差异,在给定的示例中,这将给我
+---+----+
| 2 | -5 |
| 3 | 4 |
+---+----+
可行吗?
答案 0 :(得分:3)
一种方法使用窗口函数。这样的事情有效:
select distinct type,
(first_value(value) over (partition by type order by time asc) -
first_value(value) over (partition by type order by time desc)
) as diff
from t;
不幸的是,Postgres没有first_value()
聚合函数。
您也可以使用array_agg()
:
select distinct type,
((array_agg(value order by time asc))[1] -
(array_agg(value order by time desc))[1]
) as diff
from t
group by type;