我有一個表示時間序列的串列。資料型別并不重要,但之后的任何內容timestep2都可能是NULL.
| id | timestep1 | timestep2 | timestep3 | timestep4 |
|----|-----------|-----------|-----------|-----------|
| a | foo1 | bar1 | baz1 | qux1 |
| b | foo2 | bar2 | baz2 | NULL |
我正在嘗試檢索更適合建模的資料視圖。我的建模用例要求我將每個時間序列(行)分解為代表每個步驟各自“狀態”的行。那是:
| id | timestep1 | timestep2 | timestep3 | timestep4 |
|----|-----------|-----------|-----------|-----------|
| a | foo1 | NULL | NULL | NULL |
| a | foo1 | bar1 | NULL | NULL |
| a | foo1 | bar1 | baz1 | NULL |
| a | foo1 | bar1 | baz1 | qux1 |
| b | foo2 | NULL | NULL | NULL |
| b | foo2 | bar2 | NULL | NULL |
| b | foo2 | bar2 | baz2 | NULL |
我怎樣才能在 PostgreSQL 中做到這一點?
uj5u.com熱心網友回復:
用 UNION.
select id, timestep1, timestep2, timestep3, timestep4
from my_table
union
select id, timestep1, timestep2, timestep3, null
from my_table
union
select id, timestep1, timestep2, null, null
from my_table
union
select id, timestep1, null, null, null
from my_table
order by
id,
timestep2 nulls first,
timestep3 nulls first,
timestep4 nulls first
在Db<>fiddle 中測驗它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/361555.html
標籤:PostgreSQL的 时间序列
