How to use an ALIAS in a PostgreSQL ORDER BY clause?

独自空忆成欢 提交于 2019-11-26 21:39:10

问题


I have the following query:

select 
    title, 
    ( stock_one + stock_two ) as global_stock

from product

order by
    global_stock = 0,
    title;

Running it in PostgreSQL 8.1.23 i get this error:

Query failed: ERROR: column "global_stock" does not exist

Anybody can help me to put it to work? I need the availale items first, after them the unnavailable items. Many thanks!


回答1:


You can always ORDER BY this way:

select 
    title, 
    ( stock_one + stock_two ) as global_stock
from product
order by 2, 1

or wrap it in another SELECT:

SELECT *
from
(
    select 
        title, 
        ( stock_one + stock_two ) as global_stock
    from product
) x
order by (case when global_stock = 0 then 1 else 0 end) desc, title



回答2:


One solution is to use the position:

select  title, 
        ( stock_one + stock_two ) as global_stock
from product
order by 2, 1

However, the alias should work, but not necessarily the expression. What do you mean by "global_stock = 0"? Do you mean the following:

select  title, 
        ( stock_one + stock_two ) as global_stock
from product
order by (case when global_stock = 0 then 1 else 0 end) desc, title


来源:https://stackoverflow.com/questions/11785622/how-to-use-an-alias-in-a-postgresql-order-by-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!