I'm using SQL Server 2008.
I have table constructed the following way:
Date (datetime)
TimeIn (datetime)
TimeOut (datetime)
UserReference (nvarchar)
LocationID
My desired results are: For every hour between hour 7 (7am) and hour 18 (6pm) I want to know the user who had the highest (TimeIn
- TimeOut
) for every location. -last condition is optional-
So I've got an aggregated function which calculates the datediff
in seconds between TimeOut and TimeIn aliased as Total
I want my results to look a bit like this:
Hour 7 | K1345 | 50 | Place #5
Hour 7 | K3456 | 10 | Place #4
Hour 8 | K3333 | 5 | Place #5
etc.
What I've tried so far:
A CTE using the ROW_NUMBER()
function, partitioning by my aggregated column and ordering by it. This only returns one row.
A CTE where I do all my aggregations (including datepart(hour,date)
) and use the max
aggregation to get the highest total time in my outer query.
I know I have to do it with a CTE somehow, I'm just not exactly sure how to join the cte and my outer query.
Am I on the right track using a ROW_NUMBER()
or Rank()
?
Queries I've tried:
WITH cte as
(
SELECT * ,
rn = ROW_NUMBER() over (partition by datediff(second, [TimeIn], [TimeOut])order by datediff(second, [TimeIn], [TimeOut]) desc)
FROM TimeTable (nolock)
where DateCreated > '20131023 00:00:00' and DateCreated < '20131023 23:59:00'
)
SELECT datepart(hour,cte.DateCreated) as hour,cte.UserReference,(datediff(second, [TimeIn], [TimeOut])) as [Response Time],LocationID
from cte
where cte.rn = 1
and DATEPART(hh,datecreated) >= 7 and DATEPART(hh,datecreated) <= 18
order by hour asc
This only returns a few rows
something else I've tried:
with cte as
(
SELECT Datecreated as Date,
UserReference as [User],
datediff(second, [TimeIn], [TimeOut]) as Time,
LocationID as Location
FROM TimeTable
WHERE datecreated... --daterange
)
SELECT DATEPART(HOUR,date), cte.[User], MAX(Time), Location
FROM cte
WHERE DATEPART(hh,datecreated) >= 7 and DATEPART(hh,datecreated) <= 18
GROUP BY DATEPART(HOUR,date), cte.[User], Location
Row of sample data
Date UserRef TimeIn TimeOut locationid
2013-10-23 06:26:12.783 KF34334 2013-10-23 06:27:07.000 2013-10-23 06:27:08.000 10329