I have a simple dataset like this:
CREATE TABLE test (ts timestamp, email varchar, title varchar, hobby varchar);
insert into test values
('2017-01-01', '[email protected]', 'blah', null),
('2017-01-02', '[email protected]', null, 'expected hobby'),
('2017-01-03', '[email protected]', 'expected title', null),
('2017-01-04', '[email protected]', null, null);
And I'd like to select the most recent non-null value of title and hobby per email, using a window function. These are 'expected title' and 'expected hobby'. I'm trying this:
SELECT DISTINCT
email,
first_value(title) OVER (partition by email order by ts desc nulls last),
first_value(hobby) OVER (partition by email order by ts desc nulls last)
from test
But it doesn't seem to work. Here's a sql fiddle: http://sqlfiddle.com/#!17/6d681/2
Any idea why?
first_value(title) OVER (partition by email order by case when title is not null then ts end desc nulls last),