簡體   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