Get first non null value in a partition

143 views Asked by At

As SQL Server does not support ignore nulls in first_value function, how can we get the first non null value in a window without defining a new column?

I tried to use COALESCE(), however it didn't work as a window function.

1

There are 1 answers

0
Thom A On

As has been mentioned, FIRST_VALUE does support IGNORE NULLS (in SQL Server 2022+). As such you can do:

FIRST_VALUE(YourColumn) IGNORE NULLS OVER (PARTITION BY SomeColumn ORDER BY AnotherColumn) AS FirstValue

Emulating this for FIRST_VALUE isn't too difficult without the syntax though, just add a CASE to your ORDER BY on your column to order the NULL values later:

FIRST_VALUE(YourColumn) OVER (PARTITION BY SomeColumn ORDER BY CASE WHEN YourColumn IS NULL THEN 1 ELSE 0 END, OtherColumn)

This'll force values that are NULL to be ordered later and so can only be the first value if all the values are NULL.