2016-11-11 43 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; 
相關問題