简体   繁体   中英

SQL ORACLE SET OPERATOR

I have a practice asking to show the job_id and department_id to the departments 10,20,50 and order them in specific order as 10,50,20

My select statement

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 

MESSAGE OUTPUT IS

ORA-01785: ORDER BY item must be the number of a SELECT-list expression

You can do a conditional ordering with a case expression:

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

This will order the record according to your custom department order, then by job_id .

Since you are using Oracle, the order by clause can be shortened using decode() :

order by decode(department_id, 10, 1, 50, 2, 20, 3), job_id

Note: I don't see the point for intersect in this query, so I removed it; but if you need if for some reason, the above order by clause would still remain the same.

You have a syntax error in your statement. In the ORDER BY clause you should use

CASE department_id WHEN 10 then 1
                        WHEN 50 then 2
                        WHEN 20 then 3
                        ELSE 4
                        END

instead of

CASE department_id WHEN 10 then 1
                        WHEN 50 then 2
                        WHEN 20 then 3
                        ELSE THEN 4
                        END

Basically, you shouldn't put THEN in the ELSE clause.

There is an issue with the case statement in your query.

You have not properly used the case statement, there was a missing value in the ELSE clause.

Also, INTERSECT is not needed for the requirement mentioned by you.

You can simply go for something like this to consider 50 as 11 so that the 10-50-20 (converted to 10-11-20) order is maintained.

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

Cheers!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM