I have an annoying SQL statement that seem simple but it looks awfull. I want the sql to return a resultset with userdata ordered so that a certain user is the first row in the resultset if that users emailaddress is in the companies table.
I have this SQL that returns what i want but i think it looks awful:
select 1 as o, * from Users u where companyid = 1 and email = (select email from companies where id=1) union select 2 as o, * from Users u where companyid = 1 and email <> (select email from companies where id=1) order by o
And by the way, the emailaddress from the user table can be in many companies so there cant be a join on the emailaddress 🙁
Do you have any ideas how to improve that statement?
Im using Microsoft SQL Server 2000.
Edit: Im using this one:
select *, case when u.email=(select email from companies where Id=1) then 1 else 2 end AS SortMeFirst from Users u where u.companyId=1 order by SortMeFirst
Its way more elegant than mine. Thanks Richard L!
You could do something like this..