postgres,在缺失值时添加行
问题描述:
原谅可能是一个愚蠢的问题,但我不是一个数据库大师。postgres,在缺失值时添加行
我有一个三列的表。这里有一个例子:
stationtest | id_date | val_no3
------------+-------------+---------
27 | 1 |
27 | 2 | 7
27 | 25 |
27 | 50 | 8
27 | 75 | 9
27 | 100 | 10
30 | 1 |
30 | 14 | 7
30 | 25 |
30 | 65 | 8
30 | 75 | 9
30 | 100 | 10
我想有有一行每个值id_date缺少新的表和它结合stationtest数, 像这样的:
stationtest | id_date | val_no3
------------+-------------+---------
27 | 1 |
27 | 2 | 7
27 | 3 |
27 | 4 |
27 | 5 |
27 | 6 |
27 | (...) |
27 | 25 |
27 | 26 |
27 | 27 |
27 | (...) |
27 | 50 | 8
27 | (...) |
27 | 75 | 9
27 | (...) |
27 | 98 |
27 | 99 |
27 | 100 | 10
30 | 1 |
30 | 2 | 7
30 | 3 |
30 | 4 |
30 | 5 |
30 | 6 |
30 | (...) |
30 | 25 |
30 | 26 |
30 | 27 |
30 | (...) |
30 | 50 | 8
30 | 75 | 9
30 | (...) |
30 | 98 |
30 | 99 |
30 | 100 | 10
我有这个查询,但我不知道如何使它为每个站测试工作:
insert into tabletest (id_date)
select i
from generate_series(1, (select max(id_date) from tabletest)) i
left join tabletest on tabletest.id_date = i
where tabletest.id_date is null;
这是可能的吗? 谢谢你的帮助。
答
试试这个:
DO $$
DECLARE
st_test integer;
i integer;
BEGIN
FOR st_test in (SELECT distinct stationtest FROM tabletest) LOOP
EXECUTE 'INSERT INTO test(stationtest, id_date) SELECT $1 as stationtest, generate_series as id_date FROM generate_series((SELECT min(id_date) FROM test), (SELECT max(id_date) FROM test))' USING st_test;
END LOOP;
END;
$$;
我没有数据方便,但一般格式应该工作。
A [SQLFiddle](http://sqlfiddle.com/)将不胜感激。 – jpmc26