Re: SQL question: GROUP BY and MAX

From: Jan Hidders <hidders_at_REMOVE.THIS.win.tue.nl>
Date: Sat, 21 Jul 2001 23:25:42 GMT
Message-ID: <9eg8q3$np8$1_at_news.tue.nl>


Matti Teppo wrote:
> Jan Hidders wrote:
> >
> > SELECT *
> > FROM revisions r1
> > WHERE r1.rev IN ( SELECT MAX(r2.rev)
> > FROM revisions r2
> > WHERE r1.firstid = r2.firstid );
>
> Yes, this works!

Great. Nice to hear. :-)

> But how come the GROUP BY can be replaced with a join between the
> main query and subquery???

Because you can often replace the aggregate function in a HAVING condition by a subquery over the same table that is joined with the main query on the grouping attributes. See for example:

SELECT a
FROM tabA
GROUP BY a
HAVING COUNT(*) = 5; This is equal to:

SELECT DISTINCT a
FROM tabA r1
WHERE ( SELECT COUNT(*)

        FROM tabA r2
        WHERE r1.a = r2.a ) = 5;

-- 
  Jan Hidders
Received on Sun Jul 22 2001 - 01:25:42 CEST

Original text of this message