I have a table in netezza (based on postgresql) like below. I need to create a new table with the NULL values for name
to be replaced with value of name
for the previous non-null row.
table1
id name time value
---------------------
1 john 11:00 324
2 NULL 12:00 645
3 NULL 13:00 324
4 bane 11:00 132
5 NULL 12:00 30
6 NULL 13:00 NULL
7 NULL 14:00 -1
8 zane 11:00 152
9 NULL 12:00 60
10 NULL 13:00 NULL
output table
name time value
---------------------
john 11:00 324
john 12:00 645
john 13:00 324
bane 11:00 132
bane 12:00 30
bane 13:00 NULL
bane 14:00 -1
zane 11:00 152
zane 12:00 60
zane 13:00 NULL
notes:
Cannot alter table1 due to permission restrictions, so a new table is the way.
Need to run this in
Netezza
(preferably) orMS Access
.
Code used to create the test data in Netezza is as below.
create temp table test (
id int
,name varchar(10)
,time time
,value int
)distribute on random;
insert into test (id, name, time, value) values(1, 'joe', '10:00', 324);
insert into test (id, name, time, value) values(2, null, '11:00', 645);
insert into test (id, name, time, value) values(3, null, '12:00', 324);
insert into test (id, name, time, value) values(4, 'bane', '10:00', 132);
insert into test (id, name, time, value) values(5, null, '11:00', 30);
insert into test (id, name, time, value) values(6, null, '12:00', null);
insert into test (id, name, time, value) values(7, null, '13:00', -1);
insert into test (id, name, time, value) values(8, 'zane', '10:00', 152);
insert into test (id, name, time, value) values(9, null, '11:00', 60);
insert into test (id, name, time, value) values(10, null, '12:00', null);
Try using the lead function. Not sure if that works with postgre, for Oracle it does. I think that can help.
This works for me in Access 2010:
It should work in other SQL dialects as well, although they may have a slightly different way of doing
TOP 1
(e.g.,LIMIT 1
is a common variant).You can achieve this with
COALESCE
function and subqueries:Try this recursive PostgreSQL query:
Notice though that this will probably issue a
SELECT
on each row. If you don't want that, you can use a view solution:This should be much faster. The idea is from this article. SQLFiddle: http://sqlfiddle.com/#!15/63f7b/1/1.
MS Access based solution