窗口函数first_value() https://www.postgresql.org/docs/current/functions-window.html允许一个相当简短而优雅的解决方案:
SELECT first_value(a) OVER (ORDER BY a IS NULL, ts) AS a
, first_value(b) OVER (ORDER BY b IS NULL, ts) AS b
, first_value(c) OVER (ORDER BY c IS NULL, ts) AS c
FROM t
LIMIT 1;
a IS NULL
评估为TRUE
or FALSE
. FALSE
排序在前TRUE
。这样,非空值首先出现。订购依据ts
(像你评论的时间戳列)接下来你就可以在一个单一的SELECT
.
如果 Postgres 支持的话,这会更简单IGNORE NULLS
. 手册: https://www.postgresql.org/docs/current/functions-window.html
SQL 标准定义了一个RESPECT NULLS
or IGNORE NULLS
选项lead
, lag
, first_value
, last_value
, and nth_value
。这不是
在 PostgreSQL 中实现:行为始终与
标准的默认值,即RESPECT NULLS
.
这是该领域标准 SQL 的少数遗漏之一。
我们也不能使用FILTER
条款。看:
- 使用附加(不同)过滤器聚合列 https://stackoverflow.com/questions/27136251/aggregate-columns-with-additional-distinct-filters/27141193#27141193
手册: https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS
只有聚合的窗口函数才接受FILTER
clause.
db<>fiddle
Old sqlfiddle http://sqlfiddle.com/#!17/dce83/1