Ordering output rows by the maximum value of three virtual columns
Ordering output rows by the maximum value of three virtual columns
От:
Guido Winkelmann <guido@unknownsite.de>
Дата:
Hi,
I'm looking for a way to sort the output rows of a SELECT expressions by the
maximum of three virtual columns of the output. Sorting it by one virtual
column seems to be no problem:
SELECT
() AS a,
FROM
ORDER BY a;
works fine.
Now, I have three different subselects, all of them positive integers, and
I'd like the rows to be sorted by the maximimum of these three columns.
I tried
SELECT
() AS a,
() AS b,
() AS c,
FROM
ORDER BY
CASE
WHEN a >
CASE
WHEN
b>c THEN b
ELSE c
END
THEN a
ELSE
CASE
WHEN
b>c THEN b
ELSE c
END
END;
but that'll tell me "ERROR: column "a" does not exist".
The following:
SELECT
() AS a,
() AS b,
() AS c,
CASE
WHEN () >
CASE
WHEN
()>()
THEN ()
ELSE ()
END
THEN ()
ELSE
CASE
WHEN
()>()
THEN ()
ELSE ()
END
END AS last_changed
FROM
ORDER BY last_changed;
works, but is very, very unelegant and takes a long time to execute even on
a small table. I suspect there are more elegant and faster ways to this.
So, how can this be done better?
Guido
Re: Ordering output rows by the maximum value of three virtual columns
От:
Bruno Wolff III <bruno@wolff.to>
Дата:
On Sun, Nov 13, 2005 at 21:12:07 +0100,
Guido Winkelmann wrote:
> Hi,
>
> I'm looking for a way to sort the output rows of a SELECT expressions by the
> maximum of three virtual columns of the output. Sorting it by one virtual
> column seems to be no problem:
>
> SELECT
> () AS a,
>
> FROM
> ORDER BY a;
>
> works fine.
>
> Now, I have three different subselects, all of them positive integers, and
> I'd like the rows to be sorted by the maximimum of these three columns.
> I tried
In 8.1 there is a greatest function that you can use instead of the
case statements.
Your other issue has to do with what is allowed in order by. From the manual:
expression can be the name or ordinal number of an output column (SELECT list
item), or it can be an arbitrary expression formed from input-column values.
So you can't make expressions with output column names.
>
> SELECT
> () AS a,
> () AS b,
> () AS c,
>
> FROM
> ORDER BY
> CASE
> WHEN a >
> CASE
> WHEN
> b>c THEN b
> ELSE c
> END
> THEN a
> ELSE
> CASE
> WHEN
> b>c THEN b
> ELSE c
> END
> END;
>
> but that'll tell me "ERROR: column "a" does not exist".
>
> The following:
>
> SELECT
> () AS a,
> () AS b,
> () AS c,
> CASE
> WHEN () >
> CASE
> WHEN
> ()>()
> THEN ()
> ELSE ()
> END
> THEN ()
> ELSE
> CASE
> WHEN
> ()>()
> THEN ()
> ELSE ()
> END
> END AS last_changed
>
> FROM
> ORDER BY last_changed;
>
> works, but is very, very unelegant and takes a long time to execute even on
> a small table. I suspect there are more elegant and faster ways to this.
>
> So, how can this be done better?
>
> Guido
>
> ---------------------------(end of broadcast)---------------------------
> TIP 6: explain analyze is your friend