https://dba.stackexchange.com/questions/119575/how-to-avoid-invoking-functions-twice-when-using-group-by-and-having