Solved

need help with limiting records returned in the query

Posted on 2016-09-23
48 Views
I have an student table and email table. The email table has several PERS emails for each student among other emails. I need a list of all students and one PERS email for the students. I try to pick the latest PERS email. However some students have more than one PERS email record for the same date. How do I say to just pick one of the many in this case.

student s
left outer join email e1
on s.student_id = e1.email_id and
e1.email_emal_code='PERS' and
e1.email_activity_date =( select max(e2.email_activity_date) from email e2 where e2. email_id = s.student_id and e2.email_emal_code='PERS' )

where
s.student_coll_code='BU'
0
Question by:happylife1234

LVL 76

Accepted Solution

slightwv (䄆 Netminder) earned 400 total points (awarded by participants)
ID: 41812752
Try this (untested, just typed it in):
``````select e1.email_email_address, s.student_name from
student s
left outer join (select email_id, email_email_address, email_email_code, row_number() over(partition by email_id order by email_id, email_activity_date desc) rn from email where email_email_code='PERS'  ) e1
on s.student_id = e1.email_id and
e1.rn=1
where
s.student_coll_code='BU'
``````
0

LVL 40

Assisted Solution

Sharath earned 100 total points (awarded by participants)
ID: 41812902
In slightwv's post, there is no harm keeping email_id in the ORDER BY of ROW_NUMBER because the rows are partitioned on email_id only. But you can take away that.
``````select e1.email_email_address, s.student_name from
student s
left outer join (select email_id, email_email_address, email_email_code, row_number() over(partition by email_id order by email_activity_date desc) rn from email where email_email_code='PERS'  ) e1
on s.student_id = e1.email_id and
e1.rn=1
where
s.student_coll_code='BU'
``````
0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Why doesn't the Oracle optimizer use my index? Querying too much data Most Oracle developers know that an index is useful when you can use it to restrict your result set to a small number of the total rows in a table. So, the obvious side…