CSPACE-5943: Rework building of SQL query to match Ray's candidate query #7 in CSPACE-5945.