【问题标题】:conditional sorting using order by使用 order by 条件排序
【发布时间】:2015-11-05 22:50:00
【问题描述】:

根据过程中的条件进行排序时:

    ...
    SELECT 
    ...
    order by formattedbookingdate 
    CASE WHEN isasc IS TRUE THEN
    asc
    ELSE
    desc
    END;
    ...

Postgres 抛出错误: 错误:“CASE”处或附近的语法错误 第 266 行:当 isasc 为真时的情况,那么

【问题讨论】:

  • 你不能像那样创建动态 SQL。 formattedbookingdate 是什么类型的列?
  • formattedbookingdate 是时间戳类型
  • @VishnuGS 希望isac 不是一个专栏? :)
  • 不是 isasc 是过程中的变量

标签: sql postgresql sql-order-by case-when


【解决方案1】:

这可能会很慢,但它有效:

SELECT 
    ...
    order by
    CASE WHEN isasc IS TRUE THEN
    formattedbookingdate
    ELSE
    TIMESTAMP 'epoch' - formattedbookingdate
    END;

Fiddle

【讨论】:

    【解决方案2】:

    我会分开条件,所以你在结束后添加asc 或desc,例如:

    td=# select * from (select generate_series(1,3) a) a order by case when true then a end asc, case when true then a end desc;
     a
    ---
     1
     2
     3
    (3 rows)
    
    td=# select * from (select generate_series(1,3) a) a order by case when false then a end asc, case when true then a end desc;
     a
    ---
     3
     2
     1
    (3 rows)
    

    是的,我会再想想我为什么要这样做:)

    【讨论】:

    • 如果你有一个相当大的select语句,过程会变得庞大
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    相关资源
    最近更新 更多