I have a table like this
DateTime start_time not null,
DateTime end_time not null,
Status_Id int not null,
Entry_Id int not null
I want to get the count of each status within a time period, where only the last started is valid for a given entry_id.
What I am using now is this (with dynamic dates):
with c (Status_Id, Entry_Id, Start_Date) AS (
select Status_Id, Entry_Id, Start_Date from tbl where
(End_Date BETWEEN '19000101' AND '21000101')
AND ((Start_Date BETWEEN '19000101' AND '21000101')
OR End_Date <= '21000101'))
select Status_Id, count(*) as cnt from
(select Entry_Id, max(start_date) as start_date from c
group by Entry_Id) d inner join
c on c.Entry_Id = d.Entry_Id
and c.start_date = d.start_date
GROUP BY Status_Id WITH ROLLUP
The problem is that it counts wrong when there are some entry_id that have multiple entries the same start_date. (I don't particularly care which status is chosen in this case, just that only 1 is chosen)
Some test data:
status_id Entry_id Start_date
496 45173 2010-09-29 18:04:33.000
490 45173 2010-09-29 18:48:20.100
495 45173 2010-09-29 19:25:29.300
489 45174 2010-09-29 18:43:01.500
493 45175 2010-09-29 18:48:00.500
493 45175 2010-09-29 21:16:02.700
489 45175 2010-09-30 17:52:12.100
493 45176 2010-09-29 17:55:21.300
492 45176 2010-09-29 18:20:52.200 <------ This is the one that gives the problems
493 45176 2010-09-29 18:20:52.200 <------ This is the one that gives the problems
The result should be
495 1
489 2
492 1 (or 493 1)