我有一个名为quantity的表:
+----------+----------+
| 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 |
+----------+----------+
我想选择它,以便我可以使用之前的非空值填充空白:
+----------+----------+
| 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
我怎么能实现这个目标?
谢谢!
答案 0 :(得分:3)
last_value(quantity ignore nulls) over (order by date rows unbounded preceding)
它是一个窗口函数,返回指定窗口中的最后一个值
答案 1 :(得分:-1)
您可以使用以下内容:
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
:确保选择最后一个已知值。