SELECT records base on previous records contents (no relationship)
I have a table开发者_如何学JAVA, Events, that has an EventId (PK), Date, EmployeeId (FK), and StatusId (FK).
I need to select a record based on criteria of the record that happened directly before it (chronologically by date) for a particular employee. I have no idea how to do this since there isn't a relationship.
I'd like to select a count of all Events, grouped by EmployeeId, where:
(a) StatusId = 1
(b) The last event by that EmployeeId (chronologically) has a StatusId of 9.Note that the preceding record for any event is not necessarily related to that employee.
*edited to note that I am using SQL Server, and that I am referencing the previous event chronologically by date!
Ok, Well, you can do a sub query i.e.
SELECT EmployeeID, COUNT(*)
FROM Events e1
WHERE (SELECT TOP 1 StatusID FROM Events e2 WHERE e1.EmployeeID = e2.EmployeeID ORDER
BY Date desc) = 9
GROUP BY EmployeeID, COUNT(*)
Events (EventId, Date, EmployeeId, StatusId)
select EmployeeId, count(*) from Events as e1
where e1.StatusId = 1
and exists (select e2.EventID from Events as e2
where e2.EmployeeId=e1.EmployeeId and e1.date > e2.date and e2.StatusId = 9 order by e2.date desc limit 1)
group by EmployeeId
something like that
精彩评论