select sum(c.cost) from (select x.num as x, y.num as y, max(priority) as maxpriority from numbers x cross join numbers y join costs c