This is cool and approximately what we need. The big issue is that the query has to work across sqlite, mysql, and postgresql. The best way to write a query like that is to use our DB layer SqlAlchemy to write the query. We can even do it in several steps that way if it helps. Check out http://docs.sqlalchemy.org/en/rel_0_9/core/tutorial.html for notes on the SqlAlchemy expression layer and using it to write queries.