Sachin Gadakh
Sachin Gadakh

Reputation: 11

Want to see query result order as written in query

I have written a query in which I want to show the order of employees as per written in the query. Query is as follow

select * from employeemaster where employeename in
 ('Sachin','Gaurav','Vinay','Shiv','Sandeep','Vaibhav','Prashant')   

I want to see the query result dislpaying Sachin first then the others and in this case the ID's of the employees is not in sequence, ex. Sachin's ID can be 4 and Vinay's ID can be 1. But as I have written Sachin in first place, then I want to see Sachin starting first in the result.

Upvotes: 0

Views: 84

Answers (2)

KeithL
KeithL

Reputation: 5594

select * from employeemaster 
join (values
    ('Sachin',1)
    ,('Gaurav',2)
    ,('Vinay',3)
    ,('Shiv',4)
    ,('Sandeep',5)
    ,('Vaibhav',6)
    ,('Prashant',7))  a(employeename ,_order) on a.employeename = employeemaster.employeename 
order by a.[_order]

Upvotes: 0

Andy Funk
Andy Funk

Reputation: 126

You can use a CTE with IDs to do the sorting and the filtering with an inner join.

WITH cte as (
    SELECT *
    FROM (VALUES
        (1,'Sachin')
        ,(2,'Gaurav')
        ,(3,'Vinay')
        ,(4,'Shiv')
        ,(5,'Sandeep')
        ,(6,'Vaibhav')
        ,(7,'Prashant')
        ) a (id, [name])
    )
SELECT em.*
FROM employeemaster em
JOIN cte
    ON em.employeename = cte.[name]
ORDER BY cte.id

Upvotes: 4

Related Questions