UEBAYASHI Masao <masao@nf.enveng.titech.ac.jp> writes:
> At last, I dumped this ranking method. Celko's suggestion was:
> SELECT T1.attrib0, T1.attrib1,
> (SELECT COUNT(DISTINCT attrib1)
> FROM Table AS T2
> WHERE (T2.attrib1 >= T1.attrib1)
> AND (T2.attrib0 = T1.attrib0)) AS rank
> FROM Table AS T1
> WHERE rank <= :n;
> or
> SELECT T1.attrib0, T1.attrib1,
> (SELECT COUNT(attrib1)
> FROM Table AS T2
> WHERE (T2.attrib1 >= T1.attrib1)
> AND (T2.attrib0 = T2.attrib0)) AS rank
> FROM Table AS T1
> WHERE rank <= :n;
> Unfortunately, neither don't run in PostgreSQL.
FWIW, this does work in current development sources, with the exception
of the final "WHERE rank ..." clause --- our parser doesn't think that
AS-names from the SELECT list are valid in WHERE, and after looking at
the SQL spec I have to agree with it. So you'd need to repeat the
sub-SELECT expression in WHERE :-(.
I don't have a clever idea at the moment for rewriting the query to
avoid the 6.5.* restrictions you're running into (no COUNT DISTINCT,
no sub-SELECTs in target lists).
regards, tom lane