I have a bit of a problem. I need to select a status, from a userID, in our database. The problem is, each userID has multiple rows, with different datestamps. To keep a history, in the database.
I’ve tried with group by UserID, but it will give me multiple rows, on some users, instead of ONLY the latest row, which is what I want.
This is my query:
select status, userid from EmployeeTable
where UserId in ('nis','rele')
and asofdate in
(select max(asofdate) from
EmployeeTable
where userid in ('nis','rele')
group by userid
)
So the EmployeeTable has the AsOfDate column, which is basically the updated-date. So I only want the row, with the highest AsOfDate, for a particular UserID.
What am I doing wrong?
I am guessing it has to do with me using the in clause. The more userid’s I put in there, the more userid’s will output multiple rows, but I need to be able to select multiple users at once, for performance.
What you are doing wrong is that you are checking for specific users and specific dates, but there is no connection between each user and their corresponding date. If a user has a record that matches the latest date of another user, you will get that record also.
Get the user id and their corresponding latest date, then join against the table again to get the status value for that record.