Calculate cluster distances in sql