I am currently running the following SQL fiddle
and am trying to get the following to be true:
I only want the set of cats that have had a last_checked value of some arbitrary time and are sick. for the sake of discussion lets make it now minus 12 hours. (sysdate - Interval '12' hour). What I am getting back is the cat that was last_checked 11 hours ago, but that cat has a more recent status of now where he is no longer sick. How can I construct a query in such a way that I ignore the old sick entry and only concern myself with the new healthy status? By that I mean ignore this result because the cat is no longer sick.
Question
So… do you want the most recent status regardless, the most recent
status of only those cats that have been sick in the given timeframe,
or only healthy cats?
I only want a status to be returned to me if it is the most recent (max) AND the status is also sick. In the fiddle it will show an example what I don’t want to happen, it will return the status of sick with the timestamp of 11 hours ago but there is a more recent one.
UPDATE
The following function:
select cat_id, last_checked, sick
from
(
select cat_id, last_checked, sick,
ROW_NUMBER() over (partition by cat_id order by last_checked desc) rn
from cats
where last_checked >= sysdate- INTERVAL '12' hour
) v
where rn = 1
and sick = 1;
provided by @podiluska only retrieves the first result. I need it to be on a cat by cat basis.
Second Update
The solution provided by Podiluska:
select cat_id, last_checked, sick
from
(
select cat_id, last_checked, sick,
ROW_NUMBER() over (partition by cat_id order by last_checked desc) rn
from cats
where last_checked >= sysdate- INTERVAL '12' hour
) v
where rn = 1;
will work on small data sets. The accepted answer (the one I used) will work most effectively on large data sets.
Ok so in case someone else runs into this same scenario that I did, you do not want to use an analytic function especially when your data is > 500 million records as mine is. What you want to do is unwrap the analytic query into a sql statement that has the following form: