473,756 Members | 1,799 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calculating Hours with Overlapping Times

All,

I have a table with start and end dates/times in it, and would like to
be able to calculate the number of hours represented, accounting for
overlapping records.

Note that I am looking for an answer on HOW to do this--I don't
necessarily need it to be written for me (although it would not go
unappreciated!) .
CREATE TABLE [dbo].[session_temp] (
[session_pk] [int] IDENTITY (1, 1) NOT NULL ,
[date_start] [smalldatetime] NULL ,
[date_end] [smalldatetime] NULL
) ON [PRIMARY]
GO

--These values make a very simplistic example,
--as they only represent one
--session,so using min and max would work in this case,
--but would not work if there
--were multiple sessions involved.

--hopefully you get the idea of what I am going for:

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10:30pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10:45pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 11pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/5/04 2am')

--the query I am looking to write would return "5"
--the one below obviously does not do what I am looking for
SELECT
SUM(CAST(DATEDI FF(ss,date_star t,date_end) AS NUMERIC(8,2))/3600)
FROM
session_temp

Thanks very much for any insight.

Phil

---
Check out my poker-only weblog at:
http://www.livejournal.com/users/chicago_phil/
Download my session-tracking spreadsheet at:
http://www.geocities.com/fibby70/
Jul 20 '05 #1
3 12821
-P-
"Phil Sandler" <ps********@hot mail.com> wrote in message news:3c******** *************** ***@posting.goo gle.com...
All,
<snip>

Thanks very much for any insight.

Phil

How about this?

Select
date_start,
max( cast( datediff(ss, date_start, date_end ) as numeric(8,2))/3600 )
from
session_temp
group by date_start ;

--
Paul Horan[TeamSybase]
Jul 20 '05 #2
"Phil Sandler" <ps********@hot mail.com> wrote in message
news:3c******** *************** ***@posting.goo gle.com...
All,

I have a table with start and end dates/times in it, and would like to
be able to calculate the number of hours represented, accounting for
overlapping records.

Note that I am looking for an answer on HOW to do this--I don't
necessarily need it to be written for me (although it would not go
unappreciated!) .
CREATE TABLE [dbo].[session_temp] (
[session_pk] [int] IDENTITY (1, 1) NOT NULL ,
[date_start] [smalldatetime] NULL ,
[date_end] [smalldatetime] NULL
) ON [PRIMARY]
GO

--These values make a very simplistic example,
--as they only represent one
--session,so using min and max would work in this case,
--but would not work if there
--were multiple sessions involved.

--hopefully you get the idea of what I am going for:

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10:30pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10:45pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 11pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/5/04 2am')

--the query I am looking to write would return "5"
--the one below obviously does not do what I am looking for
SELECT
SUM(CAST(DATEDI FF(ss,date_star t,date_end) AS NUMERIC(8,2))/3600)
FROM
session_temp

Thanks very much for any insight.

Phil

---
Check out my poker-only weblog at:
http://www.livejournal.com/users/chicago_phil/
Download my session-tracking spreadsheet at:
http://www.geocities.com/fibby70/


I assume that in addition to overlapping periods there might also be
gaps, for example, a period from 9AM to 10AM and then from 11AM
to 12PM should yield 2 hours with a 1 hour gap between 10AM and 11AM.

An approach would be to find the time from the earliest start datetime
to the latest end datetime and then subtract all gap lengths from this
amount.

CREATE TABLE Periods
(
start_period SMALLDATETIME NOT NULL,
end_period SMALLDATETIME NOT NULL,
CHECK (start_period < end_period),
PRIMARY KEY (start_period, end_period)
)

CREATE VIEW PeriodGaps (start_period, end_period)
AS
SELECT MAX(P1.end_peri od), P2.start_period
FROM Periods AS P1
INNER JOIN
Periods AS P2
ON P1.start_period < P2.start_period
GROUP BY P2.start_period
HAVING MAX(P1.end_peri od) < P2.start_period

-- Sample data
INSERT INTO Periods (start_period, end_period)
VALUES ('9AM', '10:30AM')
INSERT INTO Periods (start_period, end_period)
VALUES ('9:30AM', '11:30AM')
INSERT INTO Periods (start_period, end_period)
VALUES ('1:30PM', '3:00PM')
INSERT INTO Periods (start_period, end_period)
VALUES ('3:30PM', '5:00PM')

-- Note that SMALLDATETIME values are to the minute
SELECT ((SELECT COALESCE(DATEDI FF(MINUTE,
MIN(start_perio d),
MAX(end_period) ), 0)
FROM Periods) -
(SELECT COALESCE(SUM(DA TEDIFF(MINUTE,
start_period,
end_period)), 0)
FROM PeriodGaps)) / 60.0 AS duration_in_hrs

duration_in_hrs
5.500000

--
JAG
Jul 20 '05 #3
ps********@hotm ail.com (Phil Sandler) wrote in message news:<3c******* *************** ****@posting.go ogle.com>...
All,

I have a table with start and end dates/times in it, and would like to
be able to calculate the number of hours represented, accounting for
overlapping records.

Note that I am looking for an answer on HOW to do this--I don't
necessarily need it to be written for me (although it would not go
unappreciated!) .
CREATE TABLE [dbo].[session_temp] (
[session_pk] [int] IDENTITY (1, 1) NOT NULL ,
[date_start] [smalldatetime] NULL ,
[date_end] [smalldatetime] NULL
) ON [PRIMARY]
GO

--These values make a very simplistic example,
--as they only represent one
--session,so using min and max would work in this case,
--but would not work if there
--were multiple sessions involved.

--hopefully you get the idea of what I am going for:

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10:30pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10:45pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 11pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/5/04 2am')

--the query I am looking to write would return "5"
--the one below obviously does not do what I am looking for
SELECT
SUM(CAST(DATEDI FF(ss,date_star t,date_end) AS NUMERIC(8,2))/3600)
FROM
session_temp

Thanks very much for any insight.

Phil

---
Check out my poker-only weblog at:
http://www.livejournal.com/users/chicago_phil/
Download my session-tracking spreadsheet at:
http://www.geocities.com/fibby70/


Here's a stored procedure that I have created to do what you need:
/* This stored procedure combines any overlapping time segments into
a single segment in the temporary table #CombinedTime. Only non-
overlapping segements of time exist in this table. It then returns the
total hours for all these remaining segments.

Assumptions:
1. Date_Start <= Date_End
2. Date_Start, and Date_End are not null

Usage:
DECLARE @Total_Hours AS INT

EXEC @Total_Hours = CombinedTime

PRINT @Total_Hours
*/
CREATE PROCEDURE CombinedTime AS

DECLARE
@Date_Start AS SMALLDATETIME,
@Date_End AS SMALLDATETIME,
@Total_Hours AS INT

/* Create temporary table to contain combined information.
*/
CREATE TABLE #CombinedTime (
Date_Start SMALLDATETIME NOT NULL ,
Date_End SMALLDATETIME NOT NULL
)
/* Use a cursor to get every record from Session_Temp */
DECLARE Time_Cursor CURSOR FOR
SELECT Date_Start, Date_End
FROM Session_Temp
ORDER BY Date_Start ASC

OPEN Time_Cursor
FETCH NEXT FROM Time_Cursor INTO @Date_Start, @Date_End
WHILE (@@FETCH_STATUS != -1)
BEGIN
/* Update an existing record in the temporary table if Date_Start is
within the bounds of an existing record, and the Date_End is outside */
UPDATE #CombinedTime
SET Date_End = @Date_End
WHERE @Date_Start BETWEEN Date_Start AND Date_End
AND @Date_End > Date_End

/* Insert a record that falls completely outside previous ranges */
INSERT INTO #CombinedTime
(Date_Start, Date_End)
SELECT @Date_Start, @Date_End
WHERE NOT EXISTS (SELECT 1
FROM #CombinedTime
WHERE @Date_Start < Date_End)
FETCH NEXT FROM Time_Cursor INTO @Date_Start, @Date_End
END /* WHILE */

CLOSE Time_Cursor
DEALLOCATE Time_Cursor

/* Get the total hours from the non-overlapping segments */
SELECT @Total_Hours = SUM(DATEDIFF(HH , Date_Start, Date_End))
FROM #CombinedTime

DROP TABLE #CombinedTime

RETURN @Total_Hours
GO
Jul 20 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
9056
by: Ralph Freshour | last post by:
What's a good way to calculate the number of days between two dates in the following format: 2003-07-15 2003-08-02 I've looked at the PHP date functions but I'm still a bit lost...
11
4678
by: Max M | last post by:
I am writing a "find-free-time" function for a calendar. There are a lot of time spans with start end times, some overlapping, some not. To find the free time spans, I first need to convert the events into a list of non overlapping time spans "meta-spans". This nice ascii graph should show what I mean. 1) --- 2) ---
2
47856
by: Shaun | last post by:
Hi, I have a table called Bookings which has two important columns; Booking_Start_Time and Booking_End_Time. These columns are both of type DATETIME. Given any day how can I calculate how many hours are available between the hours of 09.00 and 17.30 so a user can see at a glance how many hours they have unbooked on a particular day (i.e. 8.5 hours less the time of any bookings on that day), can this be done with a query or do I have to...
8
4009
by: King | last post by:
Hi I have following MS Acess query Here is the query ID Name Prgm ID Client ID Date Start Time End Time Minutes C4 Trisha TIP DEK0703 7 /7 /2006 10:00:00 AM 12:00:00 PM 120
3
1850
by: jbosrock | last post by:
Hi to all, Please bear with me as I am newly experienced in basic Access 2003 only. I don't know Visual Basic or macros at all but am attempting to learn on my own. Explanation: Our fleet of trucks have been installed with a GPS tracking system that downloads into csv files all detailed information. The drivers also swipe a card for when they start their shift and when they end their shift. I then downloaded this information into...
4
1882
by: scott | last post by:
Hi! I have a table with a StartTime and EndTime and want to calculate number of hours worked. Is it possible to get a "Number" answer? E.g. 9:00am (StartTime) worked to 4:00pm (EndTime) = 7 (Hours worked) I would only ever have a single day so it doensn't need to span over different dates.
4
2450
by: Brian | last post by:
I have a 2000/2002 Access db that I use to collect and store my exercisetime using a form to enter. I wanted to see a summary of the total timefor each exercise so I have a subform that does this. Only issue is thatwhen I go over 24 hrs I get the infamous summing time issue. It would bereally easy if Access used the Excel :nn format, but it doesn't. Whycan't this be used in Access, Microsoft?????????????????..anyway Idigress. I have two...
0
1165
by: RubyRed | last post by:
Basically, I am trying to calculate each minute of an employee scheduled time during their work shift. In the table below shows only the times that the shift begin (start_minute), ended (sched_endtime) and times (dtl_start_min, dtl_length, dtl_end_min) the employee went on Break, lunch, etc... What the table does not show is the times that the employee was not on any breaks, lunch etc.. that is called OPENTIME. I am trying to retrieve the...
1
1710
by: RubyRed | last post by:
Using SQL Server 2000. Basically, I am trying to calculate each minute of an employee scheduled time during their work shift. In the table below shows only the times that the shift begin (start_minute), ended (sched_endtime) and times (dtl_start_min, dtl_length, dtl_end_min) the employee went on Break, lunch, etc... What the table does not show is the times that the employee was not on any breaks, lunch etc.. that is called OPENTIME. I am...
0
9462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9287
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10046
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9722
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8723
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7259
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6542
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3817
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.