Thanks for the links to the past threads!
I think the solution described in one of the answers works for me and generates exactly the query that I want.