2016-11-11 246 views
0

我的样品台SQL:排序 - 在相同的情况下对另一列排序

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中的其余值为空的情况下,我按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。

任何帮助将不胜感激。谢谢!

回答

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表达式删除ID值时Col1中为空,所以当你订购通过它,它会将所有的ID,其中Col1中为空一样的,但是当COL1不为空它会参加升序。

+1

谢谢!这工作像一个魅力。我不知道你可以像这样筑巢,学到新东西。 – Raizuri

0

按col1排序后,您想根据col1中的内容按id或col2排序。因为它的上升在一种情况下,并在其他降,你可以用一个减号工作:

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