Saturday, February 25, 2012

Complex ORDER BY - possible?

I want to sort recrords by two columns, but would like to order them by a fixed value in the first column.

Example.

I have an employee database, and want to sort by SKILL, YEARS_EXPERIENCE.

But I want a specific skill listed first, then all other skills.

Such as (I just made this up):

SELECT * from emp_master order by (SKILL='C#', YEARS_EXPERIENCE DESC), (SKILL <> 'C#', YEARS_EXPERIENCE DESC).

So my results would be:

C#, 10
C#, 7
C#, 5
ASP.NET, 10
ASP.NET, 9
ASP.NET, 5
SQL, 5
SQL, 4
VB, 5
VB, 3

This is handy for 'near' matches where I want a preferred result to filter to the top, but all results in some order.

Is this possible?One thing you might consider is returning the results for C# and sorting those, then UNION joining that to a result set that does NOT contain C#.|||UNION still just sorts by the common sort criteria, unless I am doing something wrong.

If I use two SQL statements, SQL A chooses 'C#' and years DESC, the SQL B chooses <> 'C#' and years DESC, and then UNION, they all come back in order of the years DESC without the C# being first on the list.|||You should be able to use a CASE statement:


SELECT * from emp_master
ORDER BY
CASE [Skill] WHEN 'C#' THEN 0 ELSE 1 END,
Skill,Years_Experience DESC
|||Yup, that'll definitely do it! :)|||EOM

No comments:

Post a Comment