2016-05-24 17 views
0

Ich habe Tabelle Aktionen, die von Zeit geordnete Reihen hatFüllung Lücken in postgresql

| 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 | 

Ich möchte ein wählen schreiben, die anstelle vorherigen sinnvollen Wert gesetzt wird von nulls

Wie dieses Ergebnis erhalten, mit 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 | 

Antwort

1
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; 

Ich habe versucht, dies mit 'Zeit' als int und 'session' als int [einfache Daten hinzufügen].

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

EDIT

Antwort auf die geänderte Frage.

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 
     ) 
+0

Großartig! Danke –

+0

Kann ich es in einer Auswahl tun, ohne die Tabelle zu aktualisieren? –

+1

@Timur siehe geänderte Antwort. –