如何在PostgreSQL ORDER BY子句中使用ALIAS? [英] How to use an ALIAS in a PostgreSQL ORDER BY clause?

查看:182
本文介绍了如何在PostgreSQL ORDER BY子句中使用ALIAS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

SELECT 
    title, 
    (stock_one + stock_two) AS global_stock
FROM
    product
ORDER BY
    global_stock = 0,
    title;

在PostgreSQL 8.1.23中运行它,我得到这个错误:

Running it in PostgreSQL 8.1.23 i get this error:

查询失败:错误:列"global_stock"不存在

有人可以帮助我将其投入工作吗?我首先需要可用的物品,之后是不可用的物品.非常感谢!

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

推荐答案

您总是可以这样ORDER BY:

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

或将其包装在另一个SELECT中:

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

这篇关于如何在PostgreSQL ORDER BY子句中使用ALIAS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆