简体   繁体   中英

fill column with last value from partition in postgresql

I'm trying to return the last value of a partition and apply it to the rest of the column

For example, if I have the below...

ID    Date      Status
1     20150101
1     20150201
1     20150301
1     20150401  void
2     20150101
2     20150201
2     20150301 

I want to return this.

ID    Date      Status
1     20150101   void
1     20150201   void
1     20150301   void
1     20150401   void
2     20150101
2     20150201
2     20150301  

I've been playing around with the below and similar to no avail.

select 
ID, 
date, 
case when status is null then last_value(status ignore nulls) 
over (partition by id order by id, date) else status end as status
from table

Any help would be appreciated.

You don't need the CASE statement:

SELECT id, date, last_value(status) OVER (PARTITION BY id ORDER BY date) AS stat
FROM table;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM