简体   繁体   中英

selecting unique row from a table- ORACLE

I have a table employee that has employee's benefit data. I have a field in the table called isenrolled if field is 1 that means employee has enrolled for benefit and if field is 0 that means not enrolled. My problem is i have multiple recs of a employee, that means Scott has two entries with isenrolled =1 and isenrolled =0. I want to select only one rec of SCOTT where his isenrolled =1 and reject the one where isenrolled =0, that way i will get only unique recs for employees who has enrolled and who has not enrolled. How do i select those employees? I tried the qry below and it doesn't work

select * FROM  employee e 
WHERE e.empid not IN( SELECT empid FROM employee  e2
WHERE e2.isenrolled =1)

First I set up some test data using:

create table t4
as select * from scott.emp

alter table t4 add (isenrolled number(10))

update t4
set isenrolled = 0

insert into t4
(select emp.*, 1
from scott.emp)

At this point the t4 table has now two records for each employee (one where isenrolled = 0 and one where isenrolled = 1) 替代文字

so I change ALLEN's data so he has "opted" out

delete from t4
where ename = 'ALLEN'
and isenrolled = 1

This query then shows the data for ALLEN (1 record) and SMITH (2 records)

select *
from t4
where ename IN ('ALLEN', 'SMITH')
order by ename

替代文字

Then to show just one record per employee (restricted to ALLEN and SMITH in this case) you could use:

select t.*
from t4 t
where isenrolled = (select MAX(isenrolled)
                    from t4
                    where t4.empno = t.empno)
and ename IN ('ALLEN', 'SMITH')

替代文字

Hope this helps

select unique(e.empid) from employee e where e2.isenrolled =1

this will give you unique list of employees who are enrolled. Is that what you want to get?

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