I have a table with timestamps, and I want to partition this table into hour-long intervals, starting at now and going backwards a couple of hours. I'm unable to get the results I need with the T-SQL DATEDIFF function, since it counts the number of times the minute hand passes 12 between the two dates - I want the number of times them minute hand passes where it is now between the timestamp and now.
Is there a straightforward way to do this in T-SQL?
Update: In response to comments, here's some sample data, the query I'm currently using and the results I'm getting, as well as the results I want.
Sample data:
TimeStamp
*********
2010-07-20 11:00:00.000
2010-07-20 10:44:00.000
2010-07-20 10:14:00.000
2010-07-20 11:00:00.000
2010-07-20 11:40:00.000
2010-07-20 10:16:00.000
2010-07-20 13:00:00.000
2010-07-20 12:58:00.000
Current query:
SELECT TimeStamp, DATEDIFF(HOUR, TimeStamp, CURRENT_TIMESTAMP) AS Diff FROM ...
Results:
TimeStamp Diff ********* **** 2010-07-20 11:00:00.000 2 2010-07-20 10:44:00.000 3 2010-07-20 10:14:00.000 3 2010-07-20 11:00:00.000 2 2010-07-20 11:40:00.000 2 2010-07-20 10:16:00.000 3 2010-07-20 13:00:00.000 0 2010-07-20 12:58:00.000 1
What I'd rather have:
-- The time is now, for the sake of the example, 13:40 TimeStamp Diff ********* **** 2010-07-20 11:00:00.000 3 -- +1 2010-07-20 10:44:00.000 3 2010-07-20 10:14:00.000 4 -- +1 2010-07-20 11:00:00.000 3 -- +1 2010-07-20 11:40:00.000 2 or 3 -- edge case, I don't really care which 2010-07-20 10:16:00.000 4 -- +1 2010-07-20 13:00:00.000 1 -- +1 2010-07-20 12:58:00.000 1
I've marked the results that changed with a +1
. Also, I don't really care if this is 0-indexed or 1-indexed, but basically, if it's now 13:40 I want the time spans that get the same value to be
12:40-13:40 1 (or 0) 11:40-12:40 2 (or 1) 10:40-11:40 3 (or 2) 09:40-10:40 4 (or 3)