Simplified the query, hoping to make it work with sqlite and postgres