Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 force a sort order

Author  Topic 

bbxrider
Starting Member

37 Posts

Posted - 2014-12-21 : 00:23:07
one of the fields I'm pulling in a select query does not have content that would allow me to 'order by' by the their values in their source table in the order I need, for example
table desired sort
pan 3
auto 4
tree 1
so if I order by their content, auto would be 1st, pan would be 2nd and tree would be 3rd
can I do something in the select to force the order I want coming right out of the query? something like change their values to 1tree, 2pan, 3auto coming out, so that an 'order by' would give me the order I want?
there is another field that would be the primary source field. So I can do something like saving the recs per the primary sort then manipulating the recs by the second order I want when I get a change in the primary but it would be easier if i can just get the order I want coming out of the query.

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2014-12-21 : 07:40:24
Where is the required sort order stored, if it is not in the table? If it is not stored anywhere, you will have to explicitly state the order by clause in the query - for example,
SELECT col1 FROM Tbl
ORDER BY
CASE col1 WHEN 'tree' THEN 1 WHEN 'pan' THEN 2 WHEN 'auto' THEN 3 END;
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-12-21 : 07:40:37
Order by case ...
Go to Top of Page

nextaxtion
Yak Posting Veteran

54 Posts

Posted - 2014-12-21 : 11:29:44
can include case in order by and give the number that u want to show accordingly.

SELECT col1 FROM Tbl
ORDER BY
CASE col1 WHEN 'tree' THEN 1 WHEN 'pan' THEN 2 WHEN 'auto' THEN 3 else 9999 END;

prithvi nath pandey
Go to Top of Page
   

- Advertisement -