ora-01791: not a selected expression

hi am geting this error am in oracle database 11gR2
 
i have query like this
select distinct empno,emname from employee   
order by departno  

Open in new window


 
how can i work around this
chalie001Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

PortletPaulfreelancerCommented:
select distinct departno, empno,emname from employee  
order by departno  

include departno in the select list
0
PortletPaulfreelancerCommented:
or, sort by columns you have selected...

select distinct empno,emname from employee  
order by empno,emname
0
johnsoneSenior Oracle DBACommented:
Because of the DISTINCT, you cannot order by a column that you are not selecting.

Think about it.  Here are 4 rows:

empno, emname, departno
1, Ted, 5
1, Ted, 3
2, George, 4
2, George, 2

What order should the data come out it?  Depends on which departno survives the distinct operation.  They could come out in either order.

The way around the error is to add departno to the select list, but I'm guessing that isn't going to give you the data that you want.  So, the question you have to answer first is if an employee exists in more than one department, which one is used for sorting?
0
awking00Commented:
Another possibility -
select empno, emname from
(select empno, emname, row_number() over (partition by empno, emname order by deptno) rn
 from employee)
where rn = 1;
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
chalie001Author Commented:
correct
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Oracle Database

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.