[英]Postgres: conditional ORDER BY
Consider the table below: ( here's a db-fiddle with this example )考虑下表:(这里是这个例子的一个 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
I'd like to sort this according to primary_sort
first.我想先根据
primary_sort
对此进行排序。 If equal, the next sort field depends on the value of record_id
: if two rows has the same record_id
, then sort them by record_sort
.如果相等,则下一个排序字段取决于
record_id
的值:如果两行具有相同的record_id
, record_sort
对其进行排序。 Otherwise, sort them by alt_sort
.否则,按
alt_sort
对它们进行排序。 I think the query should look something like this:我认为查询应该是这样的:
select * from example
order by
primary_sort,
case
when [this_row].record_id = [other_row].record_id
then record_sort
else alt_sort
end
;
Expected output:预期 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
Here's some pseudocode in Java, showing my intent:这是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);
}
}
(this is a minimal, reproducible example. Similar SO questions I've found on conditional order by
are not applicable, because my condition is based on values in both rows (ie [this_row].record_id = [other_row].record_id
)) (这是一个最小的、可重复的示例。我在条件
order by
中发现的类似 SO 问题不适用,因为我的条件基于两行中的值(即[this_row].record_id = [other_row].record_id
))
You can do what you describe using window functions.您可以使用 window 函数执行您描述的操作。 Something like this:
像这样的东西:
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;
This does not return the results you specify.这不会返回您指定的结果。 But some variation is probably what you intend.
但是一些变化可能是你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.