如何使用别名在PostgreSQL的ORDER BY子句?(How to use an ALIAS

2019-06-26 17:34发布

我有以下查询:

select 
    title, 
    ( stock_one + stock_two ) as global_stock

from product

order by
    global_stock = 0,
    title;

在PostgreSQL的23年8月1日运行它,我得到这个错误:

查询失败:ERROR:列“global_stock”不存在

任何人都可以帮我把它的工作? 我需要availale项目第一,之后他们unnavailable项目。 非常感谢!

Answer 1:

您可以随时ORDER BY这种方式:

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

或换用另一种选择:

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


Answer 2:

一个解决方案是使用的位置:

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

然而,别名应该工作,但不一定表达。 你说的“global_stock = 0”是什么意思? 你的意思是以下几点:

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


文章来源: How to use an ALIAS in a PostgreSQL ORDER BY clause?