SQL:排序依据 - 在绑定的情况下对另一列进行排序

时间:2016-11-11 19:56:35

标签: sql postgresql sql-order-by

我的示例表

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。

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

SELECT *
FROM
    Table
ORDER BY
    Col1 DESC nulls last,
    ,CASE WHEN Col1 IS NOT NULL THEN Id END ASC
    ,Col2 DESC nulls last
    ,Id

诀窍是使用case表达式在Col1为null时删除ID值,所以当你按顺序排序时,它会处理Col1为null的所有ID,但是当col1不为null时,它将参与升序按顺序排列。

答案 1 :(得分:0)

按col1排序后,您希望按ID或col2排序,具体取决于col1中的内容。由于它在一个案例中上升而在另一个案例中下降,因此您可以使用减号:

select *
from table
order by
  col1 desc nulls last,
  case when col1 is null then col2 else -id end desc nulls last;