首页 > 解决方案 > PostgreSQL 条件多重排序 by with asc/desc

问题描述

我想有条件地按多列排序,但不仅是所有列的单一排序类型(如此处所示

我想完成这样的事情(无效的sql,因为我不知道该怎么做,只是想传达这个想法):

-- assume this is wrapped by a function with a `_sort` string argument
select * from t_test 
order by
case when _sort='sort_type_1' then (
    col1 desc, col2 asc, col3 desc, col4 asc)
case when _sort='sort_type_2' then (
    col1 asc, col2 asc, col3 desc, col4 asc)
case when _sort='sort_type_3' then (
    col1 desc, col2 desc, col3 asc, col4 asc)
else (
    col4 desc, col3 asc)
end;

请注意 , , , 的顺序col1col2重要col3col4所以我不能做这样的事情:

select * from t_test
order by
col2, col4
case when _sort='sort_type_1' then (col1, col3) end desc;

这是否可以通过类似的方法实现,或者是否需要完全不同的方法?

标签: postgresql

解决方案


推荐阅读