Thread: numbered table?

numbered table?

From
"UEBAYASHI 'UMA' Masao"
Date:
I want to create a table looks like:
 num|code ---+----   1|   2   2|   3   3|   5   4|   9

from
 code ----    2    3    5    9


Actually, original (code) table is not ordered, but ``SELECT DISTINCT
...'' does good work for me. I wonder if SQL has iterator or thing
like that.

Masao


Re: [SQL] numbered table?

From
"UEBAYASHI 'UMA' Masao"
Date:
I've found a topic near my question, ranking, in ``SQL FOR
SMARTIES''. Thanks.

Masao


Re: [SQL] numbered table?

From
UEBAYASHI Masao
Date:
> I've found a topic near my question, ranking, in ``SQL FOR
> SMARTIES''. Thanks.

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.

Masao


Re: [SQL] numbered table?

From
Tom Lane
Date:
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