2012-02-03 106 views
3

我試圖按不按字母順序排列的名稱列表來排序項目。完成清單後,我試圖按照字母順序繼續其餘部分,而不是最初選擇的部分。在SQL Server 2000中按字段以字母順序排序

見例如:

輸入:

print 'Results:' 
select * from Geniuses 
    order by ('Charles Babbage', 
       'Albert Einstein', 
       'Adrien-Marie Legendre', 
       'Niels Henrik Abel') 

然後最終排序按字母順序休息...

OUTPUT:

Results: 
Charles Babbage ... details 
Albert Einstein ... 
Adrien-Marie Legendre ... 
Niels Henrik Abel ... 
Arthur Cayley ... 
... 
+0

您最初選擇的列表是有限的還是動態的? – squillman 2012-02-03 17:22:31

+0

其有限性就像一個由特定用戶選擇的最愛天才的小列表。但另一個用戶可能會從同一個天才列表中選擇不同的人。 – RetroCoder 2012-02-03 17:24:30

+0

好的,那麼它是動態的。對不起,我的意思是靜態而不是有限的... – squillman 2012-02-03 17:29:57

回答

8
select * from Geniuses 
order by 
    -- First, order by your set order... 
    case FullName 
     when 'Charles Babbage' then 1 
     when 'Albert Einstein' then 2 
     when 'Adrien-Marie Legendre' then 3 
     when 'Niels Henrik Abel' then 4 
     else 5 
    end, 
    -- Then do a secondary sort on FullName for everyone else. 
    FullName 

編輯:

我看到您的評論,它可以由每個用戶配置。在這種情況下,你必須有一個FavoriteGeniuses表跟蹤哪個用戶更喜歡哪個Geniuses,然後在該表中指定的排序順序:

select * 
from 
    Geniuses g left join 
    FavoriteGeniuses fg 
     ON fg.GeniusID = g.GeniusID 
     AND fg.UserID = @UserID 
order by 
    -- The higher the number, the first up on the list. 
    -- This will put the NULLs (unspecified) below the favorites. 
    fg.SortPriority DESC, 
    f.FullName 
4

試試這樣說:

select * from Geniuses 
order by 
    case when columnName = 'Charles Babbage' then 0 
    when columnName = 'Albert Einstein' then 1 
    when columnName = 'Adrien-Marie Legendre' then 2 
    when columnName = 'Niels Henrik Abel' then 3 
    else 4 
    end, 
    columName