fill column with last value from partition in postgresql

喜你入骨 提交于 2021-01-28 00:26:47

问题


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.


回答1:


You don't need the CASE statement:

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


来源:https://stackoverflow.com/questions/28956967/fill-column-with-last-value-from-partition-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!