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 CE7D45363F for ; Thu, 31 Mar 2005 06:09:38 +0100 (BST) 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 99839-05 for ; Thu, 31 Mar 2005 05:09:36 +0000 (GMT) Received: from alumni.cyut.edu.tw (alumni.cyut.edu.tw [163.17.7.196]) by svr1.postgresql.org (Postfix) with ESMTP id 71CA45363C for ; Thu, 31 Mar 2005 06:09:34 +0100 (BST) Received: from cyut.edu.tw (alumni [163.17.7.196]) by alumni.cyut.edu.tw (8.12.11/8.12.11) with ESMTP id j2V5Ee7Q008927 for ; Thu, 31 Mar 2005 13:14:40 +0800 From: "Lin Kun Hsin" To: "pgsql-sql" Subject: Re: A SQL Question About distinct, limit, group by, having, aggregate Date: Thu, 31 Mar 2005 13:14:40 +0800 Message-Id: <20050331050120.M45373@cyut.edu.tw> X-Mailer: Open WebMail 2.41 20041118 X-OriginatingIP: 163.17.28.64 (s9154083) MIME-Version: 1.0 Content-Type: text/plain; charset=big5 X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.252 tagged_above=0 required=5 tests=AWL, FROM_ENDS_IN_NUMS X-Spam-Level: X-Archive-Number: 200503/407 X-Sequence-Number: 20886 below is the sql schema. i hope it will help. i want the top 3 score students in every class below is the original sql solution, but when we have 100 class , we have to union 100 times? have any better performance statement? select * from ( (select * from allscore where class = 'a' order by score desc limit 3) union (select * from allscore where class = 'b' order by score desc limit 3) union (select * from allscore where class = 'c' order by score desc limit 3) ) as t1 order by class,score desc CREATE TABLE allscore ( id character varying(20) NOT NULL, "class" character(1) NOT NULL, score integer ); insert into allscore(id, class, score) values ('john','a','100'); insert into allscore(id, class, score) values ('jenny','a','70'); insert into allscore(id, class, score) values ('ken','a','59'); insert into allscore(id, class, score) values ('mary','b','85'); insert into allscore(id, class, score) values ('jacky','b','80'); insert into allscore(id, class, score) values ('lily','b','70'); insert into allscore(id, class, score) values ('kevin','b','50'); insert into allscore(id, class, score) values ('david','b','30'); insert into allscore(id, class, score) values ('tina','c','85'); insert into allscore(id, class, score) values ('tony','c','80'); insert into allscore(id, class, score) values ('bare','c','70'); insert into allscore(id, class, score) values ('vivian','c','60'); insert into allscore(id, class, score) values ('eric','c','57'); insert into allscore(id, class, score) values ('andy','c','50'); -- http://alumni.cyut.edu.tw Open WebMail Project (http://openwebmail.org)