如何在 PostgreSQL 中將列擴展為單獨的時間步長

泰泰

我有一個表示時間序列的列表。數據類型並不重要,但之後的任何內容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 中做到這一點?

克林

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

有一個更緊湊的解決方案,在處理更多時間步時可能更方便:

select distinct
    id, 
    timestep1, 
    case when i > 1 then timestep2 end as timestep2, 
    case when i > 2 then timestep3 end as timestep3, 
    case when i > 3 then timestep4 end as timestep4 
from my_table
cross join generate_series(1, 4) as i
order by 
    id, 
    timestep2 nulls first, 
    timestep3 nulls first, 
    timestep4 nulls first

Db<>fiddle 中測試它

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章