使用 Redshift 将空值替换为最后一个非空值

Replace nulls with the last non-null value using Redshift

我有一个table叫数量:

+----------+----------+
| date     | quantity |
+----------+----------+
| 30/11/17 | 90       |
+----------+----------+
| 01/12/17 |          |
+----------+----------+
| 02/12/17 |          |
+----------+----------+
| 03/12/17 | 1622     |
+----------+----------+
| 04/12/17 |          |
+----------+----------+
| 05/12/17 | 9092     |
+----------+----------+
| 06/12/17 |          |
+----------+----------+
| 07/12/17 |          |
+----------+----------+
| 08/12/17 | 2132     |
+----------+----------+
| 09/12/17 |          |
+----------+----------+
| 10/12/17 | 2889     |
+----------+----------+

我想 select 它以便我可以用以前的非空值填充空白:

+----------+----------+
| date     | quantity |
+----------+----------+
| 30/11/17 | 90       |
+----------+----------+
| 01/12/17 | 90       |
+----------+----------+
| 02/12/17 | 90       |
+----------+----------+
| 03/12/17 | 1622     |
+----------+----------+
| 04/12/17 | 1622     |
+----------+----------+
| 05/12/17 | 9092     |
+----------+----------+
| 06/12/17 | 9092     |
+----------+----------+
| 07/12/17 | 9092     |
+----------+----------+
| 08/12/17 | 2132     |
+----------+----------+
| 09/12/17 | 2132     |
+----------+----------+
| 10/12/17 | 2889     |
+----------+----------+

我在 i686-pc-linux-gnu 上使用 PostgreSQL 8.0.2,由 GCC gcc (GCC) 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)、Redshift 1.0 编译.1499

我怎样才能做到这一点?

谢谢!

有点像 last_value(quantity ignore nulls) over (order by date rows unbounded preceding)

这是一个 window 函数,returns 指定 window

中的最后一个值

您可以使用以下内容:

select date,(select t.quantity from [tablename] t where t.quantity is not null and t.date <= t1.date
order by t.date desc limit 1) from [tablename] t1;

t.quantity is not null:确保您不会在结果集中获得空值。

t.date <= t1.date:确保选择最后一个已知值。