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

前端 未结 2 462
日久生厌
日久生厌 2020-11-29 09:47

I have the following query:

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


        
相关标签:
2条回答
  • 2020-11-29 10:10

    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
    
    0 讨论(0)
  • 2020-11-29 10:18

    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
    
    0 讨论(0)
提交回复
热议问题