I am working with Netezza SQL.
I have the following table in which only the last year for each name is NULL:
CREATE TABLE MY_TABLE
(
name VARCHAR(50),
year INTEGER
);
INSERT INTO sample_table (name, year)
VALUES ('aaa', 2010);
INSERT INTO sample_table (name, year)
VALUES ('aaa', 2011);
INSERT INTO sample_table (name, year)
VALUES ('aaa', 2012);
INSERT INTO sample_table (name, year)
VALUES ('aaa', 2013);
INSERT INTO sample_table (name, year)
VALUES ('aaa', NULL);
INSERT INTO sample_table (name, year)
VALUES ('bbb', 2000);
INSERT INTO sample_table (name, year)
VALUES ('bbb', 2001);
INSERT INTO sample_table (name, year)
VALUES ('bbb', 2002);
INSERT INTO sample_table (name, year)
VALUES ('bbb', 2003);
INSERT INTO sample_table (name, year)
VALUES ('bbb', NULL);
name year
1 aaa 2010
2 aaa 2011
3 aaa 2012
4 aaa 2013
5 aaa NULL
6 bbb 2000
7 bbb 2001
8 bbb 2002
9 bbb 2003
10 bbb NULL
My Question: For these rows, I am trying to replace missing year values with the "logical year" (i.e. year + 1). The final result would look something like this:
name year
1 aaa 2010
2 aaa 2011
3 aaa 2012
4 aaa 2013
5 aaa 2014
6 bbb 2000
7 bbb 2001
8 bbb 2002
9 bbb 2003
10 bbb 2004
In a previous question (SQL: Using Window Aggregate Functions), I had attempted this problem in which any row for a name could have a missing year - but I was not able to solve this problem:
UPDATE my_table
SET Year = LAST_VALUE(Year IGNORE NULLS) OVER (PARTITION BY NAME ORDER BY Year ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 1
WHERE Year IS NULL;
#Error: Cannot use window aggregates in UPDATE
I was hoping that in this simpler version of the problem, there might be an easier way to solve this.
Can someone please show me how to do this?
Thanks!