sql - 选择最近的非空行
问题描述
我在 Postgres 中有一个带有时间戳的表和 6 列(A、B、C、D、E、F)的值。每 10 分钟将新记录附加到此表中,但是对于 B、D、F 列,实际值仅每 30 分钟获取一次,这意味着只有每 3 行不为空。
我想编写一个查询,每列输出最近的记录。我唯一想到的是写两个查询:
SELECT A,C,E
FROM data_prices
ORDER BY date_of_record DESC LIMIT 1
SELECT B,D,F
FROM data_prices
WHERE B is not null, D is not null, F is not null
ORDER BY date_of_record DESC LIMIT 1
然后将结果加入 1 个 6 列 1 行的表中。但是我不知道该怎么做,因为在文档中我发现了诸如UNION, INTERSECT, EXCEPT
附加数据之类的操作,而不是创建一个更宽的表。任何想法如何将这 2 个选择加入 1 个 6 列的表?或者也许更聪明的方法来获取表中每列的最新非 NULL 结果?
解决方案
不幸的是,Postgres 不支持lag(ignore nulls)
.
一种方法使用first_value()
:
select date_of_record, a,
first_value(b) over (order by (b is not null) desc, date_of_record desc) as last_b,
c,
first_value(d) over (order by (d is not null) desc, date_of_record desc) as last_d,
e,
first_value(f) over (order by (f is not null) desc, date_of_record desc) as last_f
from t
order by date_of_record desc
limit 1;
推荐阅读
- python - 尝试使用 python 3.5.4 运行时导入 pywinauto.application 会引发错误
- regex - 如果包含查询字符串,则将 url 重定向到新 URL 并传递字符串
- ubuntu - 无法登录到 ec2 实例,因为我将 ubuntu 的 chown 更改为另一个用户
- php - Cpanel 中的 Cron 作业 - 时区问题
- json - 如何将 db 结果行转换为嵌套的 json 格式
- react-native - 如何在本机反应中使用共享代码库制作多个应用程序变体?
- reactjs - 在 Create-React-App 测试套件中运行 axe-core 测试
- vbscript - 使用 WScript.shell 运行 sqlcmd - waitonreturn 不启动
- python - 如何使用 tensorflow 处理嵌套循环?
- python - Graphene-Python:从 Django 模型自动生成模式