Tom Tom
Tom Tom

Reputation: 352

How to filter within a Window Function PostgreSQL

I only want to filter in Window function to keep the created_at is null so I don't use WHERE clause previously. Because when I order by created_at desc it will show the null value first.

How to add a filter in this code?

select *, first_value(title) over (partition by product_id order by created_at desc)  as last_title
from t2

I try this not work:

select *, first_value(title) over (partition by product_id order by created_at desc) having (created_at is not null) as last_title
    from t2

Upvotes: 1

Views: 2615

Answers (2)

user330315
user330315

Reputation:

You can sort the NULL values to the end:

first_value(title) over (partition by product_id order by created_at desc nulls last)

Upvotes: 4

Jim Macaulay
Jim Macaulay

Reputation: 5165

Please use below condition,

select *, first_value(title) over (partition by product_id order by created_at desc)  
as last_title
from t2 where created_at is not null

Upvotes: 0

Related Questions