X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 6514F533AD for ; Fri, 6 May 2005 09:29:17 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 99893-04 for ; Fri, 6 May 2005 12:29:14 +0000 (GMT) Received: from wolff.to (wolff.to [66.93.197.194]) by svr1.postgresql.org (Postfix) with SMTP id 07A9D533AB for ; Fri, 6 May 2005 09:29:13 -0300 (ADT) Received: (qmail 17598 invoked by uid 500); 6 May 2005 12:49:23 -0000 Date: Fri, 6 May 2005 07:49:23 -0500 From: Bruno Wolff III To: Vortex Cc: pgsql-sql@postgresql.org Subject: Re: select within aggregate? Message-ID: <20050506124923.GB14417@wolff.to> Mail-Followup-To: Bruno Wolff III , Vortex , pgsql-sql@postgresql.org References: <20050506092535.060bca35.vortex25@gmx.de> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <20050506092535.060bca35.vortex25@gmx.de> User-Agent: Mutt/1.5.6i X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.009 tagged_above=0 required=5 tests=AWL X-Spam-Level: X-Archive-Number: 200505/51 X-Sequence-Number: 21364 On Fri, May 06, 2005 at 09:25:35 +0200, Vortex wrote: > Hi!! > > Of course the following is possible in various ways but i wonder > if there is an elegant and simple solution: > > A part from apache log: > remote_host varchar(50) > request_uri varchar(50) > ts timestamp with time zone > > Now i want to see which host has done how many requests. This > is not difficult: > > SELECT remote_host, count(*) FROM apache_log GROUP BY remote_host; > > But now i would like to add a column to the result which > shows the most recent requested uri for each group. > This sounds quite easy at first glance but i see no simple solution. > > I suppose with max(ts) i could acquire the time of the > most recent request within the group, but how do i get > the corresponding request_uri without doing subquerys or > something like that? You could use max(ts) as long as you can have two requests occur at the same time. This might be a reasonable assumption, but it might have been better to include a sequence so that each record would be guaranteed to have a unique key. Using DISTINCT ON to get the latest URIs is probably better. You can join that query to the one doing the count. This will probably be more efficient than executing a subquery for each remote host.