could add an explanation of the query here as it's dynamic and quite complex