Postgresql:为项目列表排序 Null+ true 和 false

标签 postgresql sorting

我需要对下表进行排序:

id  accepted  priority

156    NULL        3
157    t           6
158    t           2
159    f           5
160    f           3

首先排序是基于“已接受”列,然后是优先级。 我可以通过以下方式在某种程度上做到这一点:

ORDER BY accepted DESC , priority DESC

但是我希望列表的显示方式是接受为 NULL 的行伴随着接受为 true 的行,然后子排序将基于优先级。

因此我需要的决赛 table 是:

id  accepted  priority

157    t           6
156    NULL        3    
158    t           2
159    f           5
160    f           3

最佳答案

您可以使用 coalesce 使其在 order by 中将 NULL 替换为 true。这不会影响选择中返回的数据。

select * from table
order by coalesce(accepted,true) desc, priority desc

关于Postgresql:为项目列表排序 Null+ true 和 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44825496/

相关文章:

jQuery 根据值对 div 内的复选框进行排序

c++ - 用 vector 快速排序奇怪的错误

sql - 按每个项目至少有一个进行分组

ios - NSInvalidArgumentException原因: '-[__NSCFString > sortedArrayUsingComparator:]:

c - 如何找到数组中最短运行的最后一个索引?

SQL:根据最新更新时间戳查看最新ID

ios - 从NSMutableArray提取特定数据的更快方法?

database - 当我初始化 greenplum 时,它会打印 [FATAL] :-Errors generated from parallel processes

linux - 有什么方法可以在没有 pg_dump 的情况下迁移 postgresql 数据库吗?

python - Django 模型和 PostgreSQL 货币类型