I'm trying to group by subquery via an aggregate below (I simplified the query to its most basic form, a group by n query). 
But instead of using a max, I now need the following heuristic:
bar ranges from 0-2. I want to choose from 2,0,1 in that order. But I then want to original join on the original value of bar.
Can I write a custom aggregate function to return the right property? I'm a little lost on how the two would be combined.
SELECT 
    FOO.bar2
FROM
   FOO
INNER JOIN(
    SELECT
        FOO.id,
        custom_aggrgate(bar)
    FROM
        FOO                    
    GROUP BY
        FOO.id            
    ) b ON FOO.bar = inverse_of_custom_aggrgate(bar) -- get org. value of bar to join by
 
     
    