• This was real fun. So was the subsequent discussion. I really ought to get back to looking at QOTD regularly as there seem to be some real gems around now instead of the dire stuff of 6 months ago.

    I got the right answer by applying a logically wrong method which I've used before (pretend that any aggregates in the having clause but not in the select clause are added to the select clause, that the having clause then operates on the result of the combined select and group by clauses, and that after executing the having clause any spurious additions to the select clause are discarded so that the result has only the required columns). Although this is far from what logically happens it usually delivers the same results (if I've read the standard correcly, that "usually" is actually "always", so that doing it that way - if it were efficient - would be a valid option for an optimizer).

    Tom