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

查看:27
本文介绍了如何在 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天全站免登陆