gpt4 book ai didi

sql - 分组中第一行和最后一行之间的差异

转载 作者:行者123 更新时间:2023-11-29 14:09:32 35 4
gpt4 key购买 nike

我从非常复杂的查询中获取了这张表,也就是说,它不可能自己加入。行按时间排序。

type, value, time
+---+----+
| 2 | 2 |
| 2 | 7 |
| 3 | 20 |
| 3 | 16 |
+---+----+

我需要计算每个类型分组的第一个值和最后一个值之间的差异,在给定的示例中这将给我

+---+----+
| 2 | -5 |
| 3 | 4 |
+---+----+

是否可行?

最佳答案

一种方法使用窗口函数。像这样的东西有效:

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;

关于sql - 分组中第一行和最后一行之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46045405/

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