使用order by的条件排序

时间:2015-08-13 05:40:31

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

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

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

Postgres抛出错误: 错误:语法错误在或附近" CASE" 第266行:当isasc为真时

2 个答案:

答案 0 :(得分:1)

我会分开条件,因此您在结束后添加ascdesc,例如:

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)

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

答案 1 :(得分:1)

这可能会很慢但是有效:

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

Fiddle