2015-04-27 32 views
1

我有一個SQL(Vertica的)數據庫,看起來像這樣的表格數據...回填土的時間序列數據,SQL

 ts src val 
--------------------------------- 
10:25:10 C 72 
10:25:09 A 13 
10:25:08 A 99 
10:25:05 B 22 
10:25:02 C 71 

我需要「旋轉」入列,並通過回填最後已知值src列就像這樣。

 ts a_val b_val c_val 
---------------------------- 
10:25:10 13 22 72 
10:25:09 13 22 71 
10:25:08 99 22 71 
10:25:05 null 22 71 
10:25:02 null null 71 

我知道提前src的所有可能值。

+0

你說得對。我更新了這個例子。 –

回答

0

可能最簡單的方法是使用相關的子查詢。這不一定有最好的表現:

select t.ts, 
     (select t2.val from table t2 where t2.ts <= t.ts and t2.src = 'a' order by t2.ts desc) as val_a, 
     (select t2.val from table t2 where t2.ts <= t.ts and t2.src = 'b' order by t2.ts desc) as val_b, 
     (select t2.val from table t2 where t2.ts <= t.ts and t2.src = 'c' order by t2.ts desc) as val_c 
from table t; 

table(ts, src, val)的索引可以幫助子查詢比Vertica的其他數據庫。

+0

Vertica不使用索引。 – Kermit