While I can't offer any better solutions (because I haven't really spent any time thinking on the problem), it might help to know
you're having issues. In relational theory, a SELECT statement is a view transformation on each row in the resulting (often temporary) table from the JOIN clause (modified by the GROUP BY clause). The WHERE clause is a limiter on that table. Given that you want to do a transformation crossing rows, that's where your problem is. Essentially, you need to create a table where the column you're interested in appears twice in each row so that your SELECT function can work on a given row.