0

I have two tables Emp & Emp_Details

Emp -> EmpId, EmpName
Emp_Details -> EmpDetailId, Domain, Year, Date_of_record

Each employee has many domains, where their perfomance is measured, and it can be measured more than once a year.

So emp1 can have more than one recodes in Emp_Details for Domain1 for year 2015.

Now I want to fetch latest records per Domain per year for an employee.

Currently I'm fetching using two nested FOR loops in Java, i.e. one FOR loop for each factor and another inner FOR loop for each year fetching latest Date_of_record.

How should I optimize it? I'm using PL/SQL.

6
  • can you at least post a snippet of your code? Commented Nov 26, 2015 at 11:49
  • @Vance sorry due to some proprietary issue, I'll not be able to post the code. Really sorry. Commented Nov 26, 2015 at 12:00
  • @jarlh, yes it has, updated my answer Commented Nov 26, 2015 at 12:11
  • 1
    @reiley Nobody wants to steal your code, especially as it is apparently not very optimal. Commented Nov 26, 2015 at 12:55
  • @DavidAldridge, haha, still cant do. I was just helping a friend, it was not mine. Thank you. Commented Nov 26, 2015 at 14:33

2 Answers 2

1

Do a GROUP BY, use MAX to find that years latest date (for each group).

select e.EmpName, ed.Domain, ed.Year, MAX(ed.Date_of_record)
from Emp e
  left join Emp_Details ed ON e.EmpId = ed.EmpId
group by e.EmpName, ed.Domain, ed.Year
Sign up to request clarification or add additional context in comments.

Comments

0

Hello you can also try Analytical function to suffice your requirement. Let me know if this helps

SELECT a.empid,
  a.empname,
  a.domain,
  a.dor
FROM
  (SELECT e.EMPID,
    e.EMPNAME,
    ed.DOMAIN,
    ed.Date_of_record dor,
    ROW_NUMBER() OVER(PARTITION BY ed.EMPID,ed.DOMAIN ORDER BY ed.Date_of_record DESC) rnk
  FROM emp e,
    emp_details ed
  WHERE ed.empid = e.empid
  )a
WHERE a.rnk = 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.