如何在SQL中按特定组排序

时间:2014-03-06 03:01:28

标签: mysql sql

我需要像这样查询:

按照以下职位的顺序显示员工的所有详细信息:总监,监督员,工程师和秘书。

Employees表结构如下:

(的的Employee_ID 下,名字,姓氏,JOB_ID)

Jobs平板电脑结构如下:

(的 JOB_ID 下,JOB_TITLE,Min_Salary,MAX_SALARY)

我如何按照这样的特定群体进行分组?

非常感谢。

3 个答案:

答案 0 :(得分:1)

select 
      * 
  from employees employees
  join jobs jobs
    on employees.job_id = jobs.job_id
 order by case
         when job_title = 'DIRECTOR' then
          1
         when job_title = 'SUPERVISOR' then
          2
         when job_title = 'ENGINEER' then
          3
         when job_title = 'CLERK' then
          4
         else
          0 end

答案 1 :(得分:0)

select case
         when job_title = 'DIRECTOR' then
          1
         when job_title = 'SUPERVISOR' then
          2
         when job_title = 'ENGINEER' then
          3
         when job_title = 'CLERK' then
          4
         else
          0
       end as seq,
       employees.*,
       jobs.*
  from employees
  join jobs
    on employees.job_id = jobs.job_id
 order by 1

答案 2 :(得分:0)

如果您使用的是MySQL(如“mysqli”标签所示),请使用字段函数:

SELECT e.*
FROM Employee e INNER JOIN
     Job J
     ON J.Job_ID = E.Job_ID
ORDER BY field(J.Job_Title, 'DIRECTOR', 'SUPERVISOR', 'ENGINEER', 'CLERK');