Order by Field in non-alphabetical order in SQL Server 2000

梦想与她 提交于 2019-12-10 20:43:27

问题


I'm trying to order items by a list of names that are not in alphabetical order. After completing the list I am trying to continue the rest in alphabetical order without the ones I initially selected.

See example:

INPUT:

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

then finally sort the rest in alphabetical order...

OUTPUT:

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

回答1:


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

EDIT:

I saw your comment that it's configurable by each user. In that case, you'd have to have a FavoriteGeniuses table that tracks which user prefers which Geniuses, and then have a sort order specified in that table:

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



回答2:


Try it like this:

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


来源:https://stackoverflow.com/questions/9132709/order-by-field-in-non-alphabetical-order-in-sql-server-2000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!