Reputation: 2685
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 ...
...
Upvotes: 3
Views: 5310
Reputation: 37388
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
Upvotes: 10
Reputation: 66697
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
Upvotes: 4