nested case statement in postgresql