填补postgresql中的空白

时间:2016-05-24 20:09:10

标签: postgresql

我有Actions表,它有按时间排序的行

|   time   | session   |
|----------|-----------|
| 16:10:10 | session_1 |
| 16:13:05 | null      |
| 16:16:43 | null      |
| 16:23:12 | null      |
| 16:24:01 | session_2 |
| 16:41:32 | null      |
| 16:43:56 | session_3 |
| 16:51:22 | session_4 |

我想写一个选择,它将放置以前有意义的值而不是空值

如何使用postgresql获得此结果?

|   time   | session   |
|----------|-----------|
| 16:10:10 | session_1 |
| 16:13:05 | session_1 |
| 16:16:43 | session_1 |
| 16:23:12 | session_1 |
| 16:24:01 | session_2 |
| 16:41:32 | session_2 |
| 16:43:56 | session_3 |
| 16:51:22 | session_4 |

1 个答案:

答案 0 :(得分:2)

update  Actions a
set session  = (
    select session 
      from Actions 
     where time = (
            select max(time) from Actions b 
             where b.time < a.time and session is not null
      )
) where session is null;

我试着用'time'作为int,'session'作为int [更容易添加数据]。

drop table Actions;    
create table Actions (time int, session int);    
insert into Actions values (1,10),(2,null),(3,null),(4,2),(5,null),(6,3),(7,4);    
select * from Actions order by time;    
update  Actions a ...;    
select * from Actions order by time;

enter image description here

  

修改

回复您修改过的问题。

select  a1.time, a2.session 
from    Actions a1
        inner join 
        Actions a2
        on a2.time = (
         select max(time) from Actions b 
             where b.time <= a1.time and session is not null
        )