postgres,在缺失值时添加行

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; 

这是可能的吗? 谢谢你的帮助。

+0

A [SQLFiddle](http://sqlfiddle.com/)将不胜感激。 – jpmc26

试试这个:

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; 
$$; 

我没有数据方便,但一般格式应该工作。

+0

谢谢你的回答,它可能是好的,但它不起作用,因为我需要为每个工作站添加一个数字,当我在我的示例中添加一行时。 – Leasye

+0

嗯,我已经编辑它考虑到这一点。 –

+0

我试过了,但是我有一个错误: [错误] 1.0:语法错误,意外字符;你知道该怎么办? (我有postgres 9.3.1 btw) – Leasye