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 69CFD534D5 for ; Thu, 31 Mar 2005 13:19:05 +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 10751-04 for ; Thu, 31 Mar 2005 12:18:59 +0000 (GMT) Received: from alumni.cyut.edu.tw (alumni.cyut.edu.tw [163.17.7.196]) by svr1.postgresql.org (Postfix) with ESMTP id EA05C52972 for ; Thu, 31 Mar 2005 13:18:57 +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 j2VCO3Mr020405 for ; Thu, 31 Mar 2005 20:24:03 +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 20:24:03 +0800 Message-Id: <20050331121514.M9051@cyut.edu.tw> X-Mailer: Open WebMail 2.41 20041118 X-OriginatingIP: 219.68.129.99 (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.327 tagged_above=0 required=5 tests=AWL, FROM_ENDS_IN_NUMS X-Spam-Level: X-Archive-Number: 200503/411 X-Sequence-Number: 20890 Actually, i have a method to solve this problem. But i really want to know, we have to write more statement to do one thing? First step, we have to create 2 sequence. Let call them "foo" and "foo1". create sequence foo; create sequence foo1; then, you can run below statement, and you will see the result that is we want. select setval('foo',1); select setval('foo1',1); select id, score, class from ( select id, score, ph1.class , sequence1, sequence2, CASE WHEN ph1.cc > 5 THEN ph3.sequence + 4 ELSE ph3.sequence + ph1.cc - 1 END as tail from (select class, count(*) as cc from allscore group by class) as ph1 join (select id, class, score, nextval('foo') as sequence1, currval('foo') as sequence2 from (select * from allscore order by class, score desc) as t2) as ph2 on (ph1.class = ph2.class) join (select distinct on (class) class, nextval('foo1'), currval('foo1') as sequence from ( select id , score , class from allscore order by class, score desc) as t6) as ph3 on (ph2.class = ph3.class) order by ph1.class , score desc ) as con where sequence2 <= tail; -- http://alumni.cyut.edu.tw Open WebMail Project (http://openwebmail.org)