假設我有一個如下所示的當前表:
location status price
A sold 3
我有一個看起來像這樣的歷史表:
location field oldval_str newval_str oldvar_num newval_num created_at
A status closed sold null null 2022-06-01
A status listed closed null null 2022-05-01
A status null listed null null 2022-04-01
A price null null null 1 2022-04-01
A price null null 1 2 2022-05-01
A price null null 2 3 2022-06-01
如何在純 SQL 中構建如下所示的時態表?
location status price created_at
A listed 1 2022-04-01
A closed 2 2022-05-01
A sold 3 2022-06-01
我正在使用 PostgresDB 是方言有幫助!
我知道我可以在 Python 中做到這一點,我堅持使用歷史記錄中的欄位呼叫動態命名的列。想找到一個全SQL的解決方案。有什么資源可以指點?
uj5u.com熱心網友回復:
您可以使用這樣的查詢
SELECT
l.location,
MAX(h.newval_str) FILTER (WHERE h.field = 'status') AS status,
MAX(h.newval_num) FILTER (WHERE h.field = 'price') AS price,
h.created_at
FROM locations l
LEFT JOIN history h ON h.location = l.location
GROUP BY l.location, h.created_at
ORDER BY h.created_at
請看演示
在這里,locations表與history表連接以獲取所有可用location行,即使是那些值從未更改過的行,并且history表不包含任何關于它們的行。
如果您不需要它,只需history單獨使用該表即可。
SELECT
location,
MAX(newval_str) FILTER (WHERE field = 'status') AS status,
MAX(newval_num) FILTER (WHERE field = 'price') AS price,
created_at
FROM history
GROUP BY location, created_at
ORDER BY created_at
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/492787.html
標籤:sql PostgreSQL 数据库
