Can I specify the order in an ORDER BY clause in a SQL Statement?
February 19, 2009 9:18 AM
Subscribe
Can I specify the order in an ORDER BY clause in a SQL Statement? If not then what is the best way of doing the following query?
Can I specify the order in an ORDER BY clause in a SQL Statement so that it is neither ASC or DESC?
or if I can't - which I think is the answer after searching in vain on Google - then what is an alternative to solve this seemingly easy problem.
Employee directory. Each employee is assigned to a department. Many but not all employees are assigned to a second department. The directory lists the employees by last name.
What needs to happen is that if a department (say # 3) is queried, all persons who are assigned either primarily or secondarily to that department get listed, but the order must be by Primary department, lastname, THEN just lastname.
Thus if a query is for department 3 then the output must be
Name DEPT SECONDARY DEPT
Johnson, J. 3 1
Jones,M. 3
Moss, P . 3 4
Adams, J. 4 3
Johnson.Q 1 3
(note that it doesn't matter what department the secondary users are in, that can be sorted by just last name)
The select statement I have is something like this;
SELECT employee.id, employee.lname, employee.fname, employee.department, employee.secondarydepartment FROM EMPLOYEES WHERE (employees.department = "3" OR employees.secondarydepartment = "3" ORDER BY *huh*? (this is where I am stuck.)
Problem is there are at least six departments, each assigned a number, so using ORDER BY Department won't work if it is in the middle.
I am toying with the ideal of creating a second table, something like employeesaffiliation and then doing a JOIN, complicated, but I think I can do it - unless SQL experts can point me on the right path. I admit I am out of my league with more than simple queries.
posted by xetere to computers & internet (9 comments total)
3 users marked this as a favorite
SELECT employee.department, * FROM employees WHERE employees.department = "3"
UNION
SELECT employee.secondarydepartment, * FROM employees WHERE employees.secondarydepartment = "3"
ORDER BY 1
If you union the two queries together, you can order by a column... in this case, indicated by it's position, 1, rather than its name.
posted by the jam at 9:26 AM on February 19