我有一个练习,要求向部门10,20,50显示job_id和department_id,并以10,50,20的特定顺序对其进行排序
我的选择语句
select job_id,department_id
from employees
INTERSECT
select job_id,department_id
from employees
where department_id IN (10,20,50)
ORDER BY 2,CASE department_id WHEN 10 then 1
WHEN 50 then 2
WHEN 20 then 3
ELSE THEN 4
END
消息输出是
ORA-01785:ORDER BY项目必须是SELECT列表表达式的编号
case
表达式进行条件排序:select job_id, department_id
from employees
where department id in (10, 20, 50)
order by
case department_id
when 10 then 1
when 50 then 2
when 20 then 3
end,
job_id
这将根据您的自定义部门订单,然后按job_id
来订购记录。由于您使用的是Oracle,因此可以使用
order by
缩短decode()
子句:
order by decode(department_id, 10, 1, 50, 2, 20, 3), job_id
注意:在此查询中没有看到intersect
的要点,因此我将其删除;但是如果出于某些原因需要,上述order by
子句将保持不变。
CASE department_id WHEN 10 then 1
WHEN 50 then 2
WHEN 20 then 3
ELSE 4
END
代替
CASE department_id WHEN 10 then 1 WHEN 50 then 2 WHEN 20 then 3 ELSE THEN 4 END
基本上,您不应将THEN
放在ELSE
子句中。
case
语句存在问题。您没有正确使用case
语句,ELSE
子句中缺少值。
此外,您提到的要求也不需要INTERSECT
。
您可以简单地将50视为11,这样可以维持11-50-20的顺序。
SELECT
JOB_ID,
DEPARTMENT_ID
FROM
EMPLOYEES
WHERE
DEPARTMENT_ID IN (
10,
20,
50
)
ORDER BY
DECODE(DEPARTMENT_ID, 50, 11, DEPARTMENT_ID) , JOB_ID
干杯!