PostgreSQL-条件排序 [英] PostgreSQL - conditional ordering

查看:318
本文介绍了PostgreSQL-条件排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:

 键|日期|标志
--------------------------
1 now()true
2 now()-1 hour true
3 now()+ 1 hour true
4 now()false
5 now()-1 hour false
6 now()+ 1 hour false

我想要以下排序:




  • 首先,所有带有 flag = false 的行。这些行必须使用 date asc 排序。

  • 然后,所有其他行( flag = true )。但是,这些行必须使用 date desc 排序。



以下是查询是否正确?

 
select *
from test
其中flag = false
按日期排序asc

合并所有

select *
from test
其中flag = true
按日期排序desc

是否有更好的方法?

I是否将工会全部保持行的排序,并因此将两个内部查询的输出连接起来?不知道如何根据条件重复的列



更新



小提琴可以在这里找到: http: //rextester.com/FFOSS79584

解决方案

可以使用 CASE ,例如:

  select * 

测试
标志
,如果标志然后日期结束desc
的情况,如果不标志然后日期结束asc


I have the following table:

key | date         | flag
--------------------------
1    now()           true
2    now() - 1 hour  true
3    now() + 1 hour  true
4    now()           false
5    now() - 1 hour  false
6    now() + 1 hour  false

I want the following sorting:

  • First, all rows with flag = false. These rows must be sorted with date asc.
  • Then, all other rows (flag = true). However, these rows must be sorted with date desc.

Is the following query correct?

(
    select *
    from test
    where flag = false
    order by date asc
)
union all
(
    select *
    from test
    where flag = true
    order by date desc
)

Is there a better way to do this? Will the union all keep the rows sorted, and therefore just concatenate the output of the two inner queries?

I don't know how to repeat the columns in the order by, based on a condition.

update

Fiddle can be found here: http://rextester.com/FFOSS79584

解决方案

conditional order can be performed with CASE, like here:

select *
    from test
order by 
    flag
  , case when flag then date end desc
  , case when not flag then date end asc

这篇关于PostgreSQL-条件排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆