Author here. I didn't know about first_value. Thanks for the tip!
I'll play with this later today and see if it performs any better. In any case, it makes the query easier to read, so we'll probably use this unless it somehow makes the function slower.
Thanks again!