Search code examples
sqldatabase-partitioningnetezza

Netezza LAST_VALUE filter


Am trying to create a NETEZZA table which has only the most recent records for a particular key - eg imagine a table (MYTABLE) as follows:

Col1 Col2 TIMESTAMP
xxxx xxxx 13:45
xxxx xxxx 13:46
xxxx yyyy 10:00

I would like to return a table as follows:

Col1 Col2 TIMESTAMP
xxxx xxxx 13:46
xxxx yyyy 10:00

I'm guessing I need some code along the lines of:

  Create table MYNEWTABLE as
    select *
    from MYTABLE
    WHERE rowid in
    (
    SELECT LAST_VALUE(rowid)
    OVER (PARTITION BY COL1, COL2
          ORDER BY TIMESTAMP)
          FROM MYTABLE
    )
    ORDER BY COL1,COL2
    distribute on (COL1)

However this isn't really working, can anyone please advise? (specifically how to filter the table by the last value of timestamp within the col1 / col2 partition)


Solution

  • Got it - finally! rowid was a misnomer. Credit to Shawn Fox of Netezza Community for inspiration.

      Create table MYNEWTABLE as select * from
        (select *
                ,row_number() over (
                     partition by COL1, COL2 order by TIMESTAMP desc
                                   ) row
           from MYTABLE 
        ) x
        WHERE x.row=1
        distribute on (COL1)