Reputation: 13
Using Oracle SQL, I want to select a group of people's ID, test date, and test results based on when the test was taken. My problem is that the order of priority is not in chronological order. I want to select a date in year 1. If they don't have it in year 1, I want the date from year 3. If they don't have 1 or 3, I want the date from year 2.
I used a case function to create a variable (check1) to assign a value to each row based on the priority of the year in which the test was taken. So all rows have a 1, 2, or 3 in the check1 column. (1 is highest priority, 3 is lowest.)
I know how many people fall into each group using:
SELECT ID, MIN(check1)
FROM datatable
GROUP BY ID;
Here's my problem: I also need the date that they took the test so that I can join the correct test results back to the desired date. When I try to add the date to the previous function:
SELECT ID, MIN(check1), date
FROM datatable
GROUP BY ID;
Oracle errors because the date variable is not in the GROUP BY function. However, when I put the date in the group by function, it selects all the records, not just the min(check1).
How do I get it to select one row per person with the date I want?
Thanks in advance!!
Upvotes: 1
Views: 2027
Reputation: 1269533
Often, the fastest method is a correlated subquery:
SELECT t.*
FROM datatable t
WHERE t.date = (SELECT MIN(t2.check1) FROM datatable t2 WHERE t2.id = t.id);
Or, an aggregation using KEEP
:
select id, min(check1), min(date) keep (dense_rank first order by check1 asc) as date
from datatable t
group by id;
Upvotes: 3