Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id 1CAF11337B56 for ; Thu, 23 Sep 2010 19:35:40 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 63942-03 for ; Thu, 23 Sep 2010 22:35:33 +0000 (UTC) X-Greylist: delayed 00:37:53.158319 by SQLgrey-1.7.6 Received: from zebedee.cranntara.net (zebedee.cranntara.net [91.186.7.79]) by mail.postgresql.org (Postfix) with ESMTP id 100481336DB6 for ; Thu, 23 Sep 2010 19:35:33 -0300 (ADT) Received: from [88.210.158.208] (helo=bolek.coachhouse) by zebedee.cranntara.net with esmtpsa (TLS1.0:RSA_AES_256_CBC_SHA1:32) (Exim 4.69) (envelope-from ) id 1OytnL-0001BQ-I5 for pgsql-sql@postgresql.org; Thu, 23 Sep 2010 22:57:37 +0100 Received: from [192.168.0.32] (helo=dick.coachhouse ident=tarlika) by bolek.coachhouse with esmtp (Exim 4.69) (envelope-from ) id 1OytW0-0002Yq-Uo for pgsql-sql@postgresql.org; Thu, 23 Sep 2010 22:39:40 +0100 Date: Thu, 23 Sep 2010 22:39:40 +0100 From: Tarlika Elisabeth Schmitz To: pgsql-sql@postgresql.org Subject: identifying duplicates in table with redundancies Message-ID: <20100923223940.5019475e@dick.coachhouse> X-Mailer: Claws Mail 3.5.0 (GTK+ 2.12.12; i486-pc-linux-gnu) Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.9 tagged_above=-5 required=5 tests=BAYES_00=-1.9 X-Spam-Level: X-Archive-Number: 201009/92 X-Sequence-Number: 34623 I loaded data from a spread into a interim table so I can analyze the quality of the data. The table contains an entry for every student (250K records) and his trainer. Eventually, I want to extract a unique list of trainers from it. But first of all I want to check for duplicates: 1) multiples trainer names for same trainer id 2) multiple trainer ids for same trainer name I cobbled together the SQL and it does the job but it seems rather convoluted. I would like to know how I can improve it. CREATE TABLE student ( id INTEGER NOT NULL, name VARCHAR(256) NOT NULL, trainer_id INTEGER, trainer_name VARCHAR(256), ); ==== EXAMPLE DATA 22 John 1 Macdonald 23 Jane 1 MacDonald 24 Paul 1 MacDonald 25 Dick 2 Smith 26 Bill 3 Smith 27 Kate 3 Smith ==== -- outputs trainer ids which appear under different names select trainer_id, trainer_name from ( -- different id/name combinations select distinct on (trainer_name) trainer_id, trainer_name from student where trainer_id in ( -- trainer ids with appearing with different names select distinct on (id) id from ( -- distinct trainer id-name select distinct on (trainer_id,trainer_name) trainer_id as id, trainer_name as name from student ) as trainer group by trainer.id having count (trainer.name) > 1 ) ) as y order by trainer_id -- Best Regards, Tarlika Elisabeth Schmitz