Wow, I did not expect the solution to be that involved, to be honest! Thank you a lot @Mark_Smith and @steevej for the effort!
I’m marking it as the solution since it is the one relevant for the title of the thread, although it’s clear that a better approach would be changing the data model to have something more manageable.
Thank you all!
Francesco