## Working with Time Frames in T-SQL

Author
Message
jlion
SSC Rookie

Group: General Forum Members
Points: 36 Visits: 53
Let's there's a process that begins at 1:00 and ends at 3:00.

So 1:00 belongs to hour #1. 60 minutes later it is 2:00. But what about 2:00? it belongs to hour #2.

So there are 59 minutes, 59 seconds in hour #1. The minimum time slice is a whole minute. There's no accommodation in the script for fractional minutes so those extra 59 seconds get tossed out. The same is true for a process that begins at 1:30 and ends at 2:00. There are actually 29 minutes, 29 seconds, 9999 milliseconds and so on consumed in hour 1.

If you round the 59 seconds up to a whole minute then you risk counting more minutes in a day than actually exist, as the last minute in each hour would be counted twice, once at the end of the hour, and then again at the beginning of the next hour.

The solution would be to account for fractional time slices.

Robert Davis
SSChampion

Group: General Forum Members
Points: 11931 Visits: 1666

There are not 59 minutes and 59 seconds in hour #1. There isn't even 59 minutes, 59.9999 seconds. There is 60 seconds in a minute and 60 minutes in an hour. Those are constants.

If you were counting 2:00:00 as being part of hour #1, there would be 60 minutes and 1 second in hour #1.

Test it for yourself. Count from 1:00:00 to 2:00:00 incrementing by 1 second.

Or just run the following:

Select Hour1 = DateDiff(mi, '1/1/2007 1:00 PM', '1/1/2007 2:00 PM'), Hour2 = DateDiff(mi, '1/1/2007 2:00 PM', '1/1/2007 3:00 PM'), Hour1and2Combined = DateDiff(mi, '1/1/2007 1:00 PM', '1/1/2007 3:00 PM')

Or if that doesn't convince you, run the following. You will see that if you included 2:00 as part of hour #1, it would be the 61st minute, not the 60th.

Declare @Start datetime, @End datetime
Declare
@Minutes Table (MinuteNumber int not null identity(1, 1) primary key, MyTime datetime not null)

Select @Start = '1/1/2007 1:00 PM', @End = '1/1/2007 2:00 PM'

While @Start <= @End
Begin
Insert Into @Minutes (MyTime)
Select @Start

Set @Start = DateAdd(mi, 1, @Start)
End

Select *
From
@Minutes

My blog: SQL Soldier
SQL Server Best Practices: SQL Server Best Practices
My book: Pro SQL Server 2008 Mirroring
Microsoft Certified Master: SQL Server, Data Platform MVP
Database Engineer at BlueMountain Capital Management
Jeff Moden
SSC Guru

Group: General Forum Members
Points: 382577 Visits: 43026
Heh... for the same reason most British don't measure heat in British Thermal Units?

--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair

How to post code problems
How to post performance problems
Forum FAQs
Jeff Moden
SSC Guru

Group: General Forum Members
Points: 382577 Visits: 43026
 Incidentally, if you're using SQL 2005, you can jump straight to the final result fairly elegantly
Glad to see that someone finally figured out that there are 30 minutes between 12:30 and 13:00 and not just 29... Nicely done, Ryan.

--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair

How to post code problems
How to post performance problems
Forum FAQs
RyanRandall
SSCertifiable

Group: General Forum Members
Points: 6623 Visits: 4652
Thanks Jeff

Ryan Randall

Solutions are easy. Understanding the problem, now, that's the hard part.
Ian Yates
SSCrazy Eights

Group: General Forum Members
Points: 8068 Visits: 445
Nice article. I like Ryan's elegant solution - unfortunately many of our clients are still sticking with SQL 2k (even though they could get by with Express) so I haven't played with CTEs....
The discussion about 59.59 or 60.00 in an hour is much the same as people who call midday 12am rather than 12pm, which day is 12am a part of, etc... (I know the answers, as you all would too, so no need to tell me )

Only correction is that situation #6's description is wrong - the before/after is mixed up...

Dave F-425609

Group: General Forum Members
Points: 458 Visits: 37

Hi,

I didn't read the whole article, but had a couple on the more basic points.

SELECT
COUNT(*)
FROM
[MY_EVENTS]
WHERE
---CASES 3, 4 AND 5
(([STARTING_TIME] > 7/1/2007 12:00 PM AND [STARTING_TIME] < 7/1/2007 1:00 PM)
OR ([ENDING_TIME] > 7/1/2007 12:00 PM AND [ENDING_TIME] < 7/1/2007 1:00 PM))
OR
---CASE 2
([STARTING_TIME] < 7/1/2007 12:00 PM AND [ENDING_TIME] > 7/1/2007 1:00 PM)

This could be written much more simply as

SELECT
COUNT(*)
FROM
[MY_EVENTS]
WHERE [STARTING_TIME] <= 7/1/2007 1:00 PM
AND [ENDING_TIME] >= 7/1/2007 12:00 PM --This assumes that starting_time<ending_time

Also to get the time period utilised for each row you could do something like

(((7/1/2007 1:00PM)-(START_TIME)-(CASE END_TIME<(7/1/2007 1:00PM) THEN ((7/1/2007 1:00PM)-(END_TIME)) ELSE 0))%60)*24*60

to get the number of minutes

Not criticising, it's just what I thought of what I began, and couldn't continue until I wrote it down

steve smith-401573
SSCarpal Tunnel

Group: General Forum Members
Points: 4443 Visits: 744
what format would you like us to use? dd month year, without any punctuation at all? (example: today is 17 August 2007)

the short date format, using two digits for month, day and year, is only ambiguous during the first 12 days of the month, when the order is not intuitively obvious (assuming a valid date). given that the average month is 365/12 or 30.42 days long, then ambiguity can only occur 39.5% of the time. Which is much greater precision than one gets in the form of specifications from an end user.
steve smith-401573
SSCarpal Tunnel

Group: General Forum Members
Points: 4443 Visits: 744
Robert - obviously you've never dealt with psychotherapists. Their hours range from 45 to 50 minutes.
Me Da Man
SSC Journeyman

Group: General Forum Members
Points: 88 Visits: 6

What about the situation where the Start date/times match? What about the situation where the Start and End date/times match? How does this affect the WHERE clause of the first query?

Thanks

## Permissions

 You can't post new topics. You can't post topic replies. You can't post new polls. You can't post replies to polls. You can't edit your own topics. You can't delete your own topics. You can't edit other topics. You can't delete other topics. You can't edit your own posts. You can't edit other posts. You can't delete your own posts. You can't delete other posts. You can't post events. You can't edit your own events. You can't edit other events. You can't delete your own events. You can't delete other events. You can't send private messages. You can't send emails. You can read topics. You can't vote in polls. You can't upload attachments. You can download attachments. You can't post HTML code. You can't edit HTML code. You can't post IFCode. You can't post JavaScript. You can post emoticons. You can't post or upload images.

##### Select a forum
 SQL Server 2017      SQL Server 2017 - Administration      SQL Server 2017 - Development SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 15 - Administration      SQL Server 15 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions      CosmosDB      Azure Data Lake      Azure Machine Learning Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      Question of the Day (QOD)      SQL Server Security Skills Microsoft Access      Microsoft Access Products and Books      Third Party Products         CA         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Sonasoft         SQLCentric         Golden Gate Software         Lumigent         Red Gate Software         Quest Software         ApexSQL         Idera      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss DTS Books          Discuss SQL Server 7.0 Books         Discuss SQL Server 2000 Books Notification Services      Administration Article Discussions Future Versions      SQL 12