繁体   English   中英

Postgres:有条件的 ORDER BY

[英]Postgres: conditional ORDER BY

考虑下表:(这里是这个例子的一个 db-fiddle

id   primary_sort   record_id   record_sort  alt_sort
1    2              1           11           100
2    2              2           10           101
3    3              1           12           108
4    3              1           13           107
5    3              2           14           105
6    1              2           15           109

我想先根据primary_sort对此进行排序。 如果相等,则下一个排序字段取决于record_id的值:如果两行具有相同的record_idrecord_sort对其进行排序。 否则,按alt_sort对它们进行排序。 我认为查询应该是这样的:

select * from example
order by 
  primary_sort,
  case
    when [this_row].record_id = [other_row].record_id
    then record_sort
    else alt_sort
  end
;

预期 output:

id   primary_sort   record_id   record_sort  alt_sort
6    1              2           15           109
1    2              1           11           100
2    2              2           10           101
5    3              2           14           105
3    3              1           12           108
4    3              1           13           107

这是Java中的一些伪代码,显示了我的意图:

int compareTo(Example other) {
    if (this.primary_sort != other.primary_sort)
    {
        return this.primary_sort.compareTo(other.primary_sort);
    }
    else if (this.record_id == other.record_id)
    {
        return this.record_sort.compareTo(other.record_sort);
    }
    else
    {
        return this.alt_sort.compareTo(other.alt_sort);
    }
}

(这是一个最小的、可重复的示例。我在条件order by中发现的类似 SO 问题不适用,因为我的条件基于两行中的值(即[this_row].record_id = [other_row].record_id ))

您可以使用 window 函数执行您描述的操作。 像这样的东西:

select *
from example e
order by primary_sort,
         (case when count(*) over (partition by primary_sort, record_id) > 1 then record_sort
          end) nulls last,
         alt_sort;

这不会返回您指定的结果。 但是一些变化可能是你想要的。

您可以使用解析 function 如下:

select * from example
order by primary_sort, 
 case when count(*) over (partition by primary_sort, record_id) > 1
      then record_sort else record_id end, alt_sort;

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM