【发布时间】:2016-11-11 19:56:35
【问题描述】:
我的示例表
id | col1 | col2
---+------+-----
1 | 5 | 1
11| |
8 | 1 | 2
3 | | 1
4 | 1 | (where blanks are nulls)
6 | | 4
2 | 4 | 9
9 | 7 |
10| |
我正在尝试按 col1 降序排列(最后一个为空),如果是平局(例如,行 (8, 1, 2) 和 (4, 1, )),我会喜欢按 id 升序排列。
如果col1中剩余的值为null,我再按照col2的降序排序。
所以我的结果表应该是这样的:
id | col1 | col2
---+------+-----
9 | 7 |
1 | 5 | 1
2 | 4 | 9
4 | 1 | (where blanks are nulls)
8 | 1 | 2
6 | | 4
3 | | 1
10| |
11| |
我的查询有问题。我已尝试执行以下操作,但它们似乎都无法正常工作。
/* This creates the correct ordering, but in the case of ties
they are ignored and don't follow id ascending */
select *
from table
order by
col1 desc nulls last,
col2 desc nulls last,
id asc;
-
/* When this finds a null value, it basically ignores the desc requirement of col 2 */
select *
from table
order by
col1 desc nulls last,
id asc,
col2 desc nulls last;
如果重要的话,我正在使用 PostgreSQL。
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: sql postgresql sql-order-by