SQL Server Management Studio – Order by different columns based on values in the different columns

Wrap your head around this one!

Here is an example of an order by in a SQL Statement that shows how specific you can get when ordering your data.
order by location_3,
case 
 when location_3 ='c' then
 case 
 when location_4 = '1' then location_5
 when location_4 in('2','3') then name_last
 else location
 end

when location_3 ='d' then name_last

when location_3 ='e' then
 case 
 when location_4 = '1' then location_5
 when location_4 in('2','3','4','5') then name_last
 else location
 end

when location_3 ='f' then
 case 
 when location_4 in('1','2','3') then name_last
 when location_4 in('4','5') then location_5
 else location
 end

when location_3 ='g' then
 case 
 when location_4 in('1','2','4','5') then name_last
 when location_4 = '3' then location_5
 else location
 end

else location
end

Leave a Reply