X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id 9F2949DC9A0 for ; Fri, 17 Feb 2006 20:47:22 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 00683-07 for ; Fri, 17 Feb 2006 20:47:25 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey- Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id C6BA99DC97F for ; Fri, 17 Feb 2006 20:47:19 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.13.1/8.13.1) with ESMTP id k1I0lM67014048; Fri, 17 Feb 2006 19:47:22 -0500 (EST) To: Jan Danielsson cc: pgsql-sql@postgresql.org Subject: Re: two count columns? In-reply-to: <43F662C4.9070402@gmail.com> References: <43F662C4.9070402@gmail.com> Comments: In-reply-to Jan Danielsson message dated "Sat, 18 Feb 2006 00:56:52 +0100" Date: Fri, 17 Feb 2006 19:47:22 -0500 Message-ID: <14047.1140223642@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.11 required=5 tests=[AWL=0.110] X-Spam-Score: 0.11 X-Spam-Level: X-Archive-Number: 200602/222 X-Sequence-Number: 24232 Jan Danielsson writes: > So the only thing I'm missing is the total number of log entries > matching the from_ip, but that's where I'm stuck. My instinct is to try > to use subqueries: > select from_ip, count(from_ip) as entries, count(select * from log where > ...) as tot_entries, max(ts)::timestamp(0) as last_access from log where > to_port=22 and direction='in' group by from_ip > ...but count() doesn't take a subquery afaik, and how would I match the > from_ip in the inner select with the outer one? I think you want something like select ..., (select count(*) from log loginner where from_ip = log.from_ip) ... from log ... You need to attach an alias to either the inner or the outer use of "log" so that you can refer to the outer one from the inner SELECT. Here I chose to alias the inner one, but it might be clearer to alias the outer: select ..., (select count(*) from log where from_ip = logouter.from_ip) ... from log logouter ... Note that anything like this is going to be pretty expensive if your log table is large. You might want to think about something involving another layer of GROUP BY instead. regards, tom lane