Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id 906AE7661B8 for ; Thu, 21 Jun 2012 14:49:12 -0300 (ADT) Received: from ns0.azuni.net ([217.25.25.3] helo=azuni.net) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1ShlVG-00089B-0q for pgsql-sql@postgresql.org; Thu, 21 Jun 2012 17:49:11 +0000 Received: (qmail 42382 invoked by uid 89); 21 Jun 2012 17:48:57 -0000 Received: by simscan 1.4.0 ppid: 42377, pid: 42379, t: 0.0315s scanners: attach: 1.4.0 clamav: 0.95.2/m:51/d:9540 Received: from unknown (HELO ?217.25.27.27?) (rihad@stream.az@217.25.27.27) by ns0.azuni.net with ESMTPA; 21 Jun 2012 17:48:57 -0000 Message-ID: <4FE35E88.6010805@stream.az> Date: Thu, 21 Jun 2012 22:48:56 +0500 From: Rihad Reply-To: Rihad User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20120430 Thunderbird/12.0.1 MIME-Version: 1.0 To: pgsql-sql@postgresql.org Subject: Need help building this query Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201206/64 X-Sequence-Number: 36718 Hi, folks. I currently need to join two tables that lack primary keys, and columns used to distinguish each record can be duplicated. I need to build statistics over the data in those tables. Consider this: TableA: row 1: foo: 123, bar: 456, baz: 789, amount: 10.99, date_of_op: date row 2: foo: 123, bar: 456, baz: 789, amount: 10.99, date_of_op: date row 3: foo: 123, bar: 456, baz: 789, amount: 10.99, date_of_op: date TableB: row 1: foo: 123, bar: 456, baz: 789, amount: 10.99, date_of_op: date Columns foo + bar + baz are used to distinguish a performed "operation": TableA.date_of_op isn't, because it can lag behind TableB. Not all different "operations" are in table B. Table B is just there so we know which "operations" are complete, so to speak (happening under external means and not under any of my control). Now, for each operation (foo+bar+baz) in table A, only *one* row should be matched in table B, because it only has one matching row there. The other two in TableA should be considered unmatched. Now the query should be able to get count(*) and sum(amount) every day for that day, considering that matched and unmatched operations should be counted separately. The report would look something like this: TableA.date_of_op TableB.date_of_op 2012-06-21 [empty] [count(*) and sum(amount) of all data in TableA for this day unmatched in TableB] 2012-06-21 2012-06-20 [count(*) and sum(amount) of all data in TableA matched in TableB for the 20-th] 2012-06-21 2012-06-19 [count(*) and sum(amount) of all data in TableA matched in TableB for the 19-th] Can this awkward thing be done in pure SQL, or I'd be better off using programming for this? Thanks, I hope I could explain this.