Обсуждение: order by a "select as" determined by case statement

Поиск
Список
Период
Сортировка

order by a "select as" determined by case statement

От
FatTony
Дата:
I'm not a db guru by any means so please forgive me if this has an easy
solution.

Scenario:

Want to sort by an alias for SELECT AGE(). Problem is the timestamps for
the SELECT AGE will be determined by the value of another column, thus
the use of CASE.

What I thought would work.

SELECT tblticket.ticketid,tblstatus.statusname,
CASE WHEN tblstatus.statusname = 'Closed'
THEN (SELECT AGE(tblticket.ticketclosed,tblticket.ticketcreated) as
ticketage)
ELSE (SELECT AGE(CURRENT_TIMESTAMP,tblticket.ticketcreated) as
ticketage) 
END
FROM tblticket CROSS JOIN tblstatus
WHERE (tblticket.reasonid = 2) AND blah, blah, blah
ORDER BY ticketage ASC

CASE apparently completely ignores the ticketage alias. Anyone know how
to get around this?

Thank You.




Re: order by a "select as" determined by case statement

От
Stephan Szabo
Дата:
On Fri, 6 Dec 2002, FatTony wrote:

> I'm not a db guru by any means so please forgive me if this has an easy
> solution.
>
> Scenario:
>
> Want to sort by an alias for SELECT AGE(). Problem is the timestamps for
> the SELECT AGE will be determined by the value of another column, thus
> the use of CASE.
>
> What I thought would work.
>
> SELECT tblticket.ticketid,tblstatus.statusname,
> CASE WHEN tblstatus.statusname = 'Closed'
> THEN (SELECT AGE(tblticket.ticketclosed,tblticket.ticketcreated) as
> ticketage)
> ELSE (SELECT AGE(CURRENT_TIMESTAMP,tblticket.ticketcreated) as
> ticketage)
> END
> FROM tblticket CROSS JOIN tblstatus
> WHERE (tblticket.reasonid = 2) AND blah, blah, blah
> ORDER BY ticketage ASC
>
> CASE apparently completely ignores the ticketage alias. Anyone know how
> to get around this?

Probably what you want is:
case when ...
then ...
else ...
end as ticketage

The aliases on the result columns of the subquery don't translate into the
alias of the case expression, but you can give the case expression an
alias instead.