Sql 在Postgres中查询时间序列表的最后一个非空值
我有一个时间序列表,如下所示:Sql 在Postgres中查询时间序列表的最后一个非空值,sql,postgresql,time-series,Sql,Postgresql,Time Series,我有一个时间序列表,如下所示: time | a | b | c | d --------------------+---------+----------+---------+--------- 2016-05-15 00:08:22 | | | | 2016-05-15 01:50:56 | | | 26.8301 | 20
time | a | b | c | d
--------------------+---------+----------+---------+---------
2016-05-15 00:08:22 | | | |
2016-05-15 01:50:56 | | | 26.8301 |
2016-05-15 02:41:58 | | | |
2016-05-15 03:01:37 | | | |
2016-05-15 04:45:18 | | | |
2016-05-15 05:45:32 | | | 26.9688 |
2016-05-15 06:01:48 | | | |
2016-05-15 07:47:56 | | | | 27.1269
2016-05-15 08:01:22 | | | |
2016-05-15 09:35:36 | 26.7441 | 29.8398 | | 26.9981
2016-05-15 10:08:53 | | | |
2016-05-15 11:08:30 | | | |
2016-05-15 12:14:59 | | | |
2016-05-15 13:33:36 | 27.4277 | 29.7695 | |
2016-05-15 14:36:36 | 27.4688 | 29.6836 | |
2016-05-15 15:37:36 | 27.1016 | | |
我想返回每列的最后一个非空值:
像这样(最佳选择):
像这样:
column | value
-------- +-------
a | 27.1016
b | 29.6836
c | 26.9688
d | 26.9981
a | b | c | d
--------+----------+---------+---------
27.1016 | 29.6836 | 26.9688 | 26.9981
或者至少是这样:
column | value
-------- +-------
a | 27.1016
b | 29.6836
c | 26.9688
d | 26.9981
a | b | c | d
--------+----------+---------+---------
27.1016 | 29.6836 | 26.9688 | 26.9981
谢谢 您可以取消PIVOT并选择最后一行:
select distinct on (v.which) t.time, v.which, v.val
from t cross join lateral
(values (a, 'a'), (b, 'b'), (c, 'c'), (d, 'd')) v(val, which)
where v.val is not null
order by v.which, t.time desc;
我建议另一个答案,但我现在看到@GordonLinoff的答案更好 时间戳|列|值 :-------- | :----- | ----: 2 | a | 2 4 | b | 4 2 | c | 3
dbfiddlelast非空last以什么顺序?@Miro。我被你的数据弄糊涂了。如果这是时间序列数据,为什么行不按时间顺序排列?你不想要最近的值吗?你完全正确-我的数据中有一个错误。这是应该订的。修正…这将按时间顺序返回最后一个非空值,这不是OP想要的。检查预期输出。数据有问题-强度正确。。。。。很抱歉……这个解决方案很简洁,但出于某种原因,Postgres在执行它时没有重用我的数据部分索引(
在t(time,“a”)上创建索引“idx\u nonnull\u a”,其中“a”不为NULL
)。有什么想法吗?@Miro。我认为它不会使用任何索引。如果可能的话,使用索引将更加复杂。
timestamp | column | value
:-------- | :----- | ----:
2 | a | 2
4 | b | 4
2 | c | 3