我試圖在標題中建議的每個 ID 中缺少日期時插入行,方法是使用日期范圍作為 MIN 和 MAX 日期。這是我擁有的表的示例:
| 設備編號 | 日期 | 速度 | 高度 |
|---|---|---|---|
| 1 | 2021-06-08 | 50 | 10 |
| 1 | 2021-06-09 | 30 | 15 |
| 1 | 2021-06-12 | 20 | 20 |
| 2 | 2021-06-07 | 10 | 15 |
| 2 | 2021-06-10 | 60 | 5 |
我想插入行,以便不可用的資訊變為 None 或 Null,如下所示:
| 設備編號 | 日期 | 速度 | 高度 |
|---|---|---|---|
| 1 | 2021-06-07 | 沒有任何 | 沒有任何 |
| 1 | 2021-06-08 | 50 | 10 |
| 1 | 2021-06-09 | 30 | 15 |
| 1 | 2021-06-10 | 沒有任何 | 沒有任何 |
| 1 | 2021-06-11 | 沒有任何 | 沒有任何 |
| 1 | 2021-06-12 | 20 | 20 |
| 2 | 2021-06-07 | 10 | 15 |
| 2 | 2021-06-08 | 沒有任何 | 沒有任何 |
| 2 | 2021-06-09 | 沒有任何 | 沒有任何 |
| 2 | 2021-06-10 | 60 | 5 |
| 2 | 2021-06-11 | 沒有任何 | 沒有任何 |
| 2 | 2021-06-12 | 沒有任何 | 沒有任何 |
如果你能看到,插入的行是針對每個“device_id”中缺失的每個日期,“speed”和“height”列輸入為“None”,這樣我就有了在使用的日期范圍內的每個日期的資訊第一張桌子。謝謝!
uj5u.com熱心網友回復:
解決方案 :
SELECT i.device_id
, d.date
, CASE WHEN t.date IS NULL THEN 'None' ELSE t.speed :: text END AS speed
, CASE WHEN t.date IS NULL THEN 'None' ELSE t.height :: text END AS height
FROM
( SELECT generate_series(min(date), max(date), interval '1 day') AS date
FROM your_table
) AS d
CROSS JOIN
( SELECT DISTINCT device_id
FROM your_table
) AS i
LEFT JOIN your_table AS t
ON t.date = d.date
AND t.device_id = i.device_id
ORDER BY i.device_id, d.date
結果 :
device_id date speed height
1 2021-06-07 00:00:00 01 None None
1 2021-06-08 00:00:00 01 50 10
1 2021-06-09 00:00:00 01 30 15
1 2021-06-10 00:00:00 01 None None
1 2021-06-11 00:00:00 01 None None
1 2021-06-12 00:00:00 01 20 20
2 2021-06-07 00:00:00 01 10 15
2 2021-06-08 00:00:00 01 None None
2 2021-06-09 00:00:00 01 None None
2 2021-06-10 00:00:00 01 60 5
2 2021-06-11 00:00:00 01 None None
2 2021-06-12 00:00:00 01 None None
看dbfiddle 中的演示
uj5u.com熱心網友回復:
正如@stickybit 所建議的,使用分步 CTE:
with dates("date") as
(
select generate_series('2021-06-07'::timestamp, '2021-06-12', interval '1 day')::date
),
device_ids(device_id) as
(
select distinct device_id from the_table
),
fulllist as
(
select *
from dates cross join device_ids
)
select device_id, "date", coalesce(speed::text,'None') speed, coalesce(height::text,'None') height
from fulllist
left join the_table using (device_id, "date")
order by device_id, "date";
我不不過以為text是的資料型別的一個很好的選擇speed和height以及對遺漏值字“無”。簡單的
select device_id, "date", speed, height
null為缺失值生成s 會更相關。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/384200.html
標籤:sql PostgreSQL的
