How can I implement IGNORE NULLS in window functions such as FIRST_VALUE and LAST_VALUE in MySQL?
For example, let’s say we have a very simple table called sales.
SaleID | CustomerID | SaleRegion |
---|---|---|
1 | 7 | CITY A |
2 | 10 | NULL |
3 | 10 | NULL |
4 | 7 | CITY A |
5 | 10 | CITY B |
6 | 10 | CITY C |
How can I get the first value of sale region partitioned by customer id?
Expected (Desired) Output:
CUSTOMERID | FIRST_VALUE(SALEREGION) |
---|---|
7 | CITY A |
7 | CITY A |
10 | CITY B |
10 | CITY B |
10 | CITY B |
2
Answers
You need to ORDER BY
SaleRegion
DESC in the window function.If one customer has multiple regions, you need to refine the Order by
fiddle
If you want to ignore nulls completely, you can always use an inner query to remove nulls before passing the values to window function or any expression.
In the given example;
Hope this helps.