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 AE55D53E02 for ; Wed, 13 Apr 2005 14:29:14 -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 11948-05 for ; Wed, 13 Apr 2005 17:29:06 +0000 (GMT) Received: from floppy.pyrenet.fr (news.pyrenet.fr [194.116.145.2]) by svr1.postgresql.org (Postfix) with ESMTP id 9035353DF6 for ; Wed, 13 Apr 2005 14:29:05 -0300 (ADT) Received: by floppy.pyrenet.fr (Postfix, from userid 106) id 36CE730952; Wed, 13 Apr 2005 19:28:19 +0200 (MET DST) From: "Matt Fulford" X-Newsgroups: pgsql.sql Subject: SQL subquery (count distinct) - Any Ideas? Date: Wed, 13 Apr 2005 18:28:36 +0100 X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 6.00.2900.2180 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2180 X-RFC2646: Format=Flowed; Original Message-ID: Lines: 30 X-Complaints-To: abuse@karoo.kcom.com X-DMCA-Complaints-To: abuse@karoo.kcom.com X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.32 To: pgsql-sql@postgresql.org X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=1.185 tagged_above=0 required=5 tests=PRIORITY_NO_NAME X-Spam-Level: * X-Archive-Number: 200504/267 X-Sequence-Number: 21160 I'm trying to write a query to return the number of different customers called on a single day. The database has a table called 'user', a table called 'caller_session' which references a 'user' record, and a table called 'call' which references a 'caller_session'. This is my current attempt: select user.name, sum((select count(distinct call.customer_id) from call where call.caller_session_id=cs.caller_session_id)) as contacted from user, caller_session cs where cs.user_id=user.user_id and date(cs.session_date) = date('2005-04-13') group by user.name; I get back a list of names and a call count (as desired), but the count is not correct! The subqery is counting the number of different customers called for each caller_session, and summing them based on the user.name field. If the same customer is called in 2 different sessions, this is being counted as 2 customers, but should be 1! The 'contacted' count calculation has to be in a subquery as above, because there are other subqueries after this one to calculate other data based on the outer query (the outer query has to be as it is here). Not quite sure where the sum, count and distinct should really go to get the required results! Any help greatly appreciated!