Q
Problem solve Get help with specific problems with your technologies, process and projects.

Aggregating time intervals

How can I aggregate intervals? Given two timestamps (one for the beginning, the other for the end of an event) I would like to know the average duration of the event.

How can I aggregate intervals? What I'm trying to do is, given two timestamps (one for the beginning, the other for the end of an event) I would like to know the average duration of the event. What's the best way to do this?

Presumably you want the average duration for a number of events, not just one. For a single event, we obtain a...

duration by "subtracting" the beginning timestamp from the end timestamp. This requires date arithmetic, which can vary wildly from one database system to the next.

Before we get started, let's create some test data.

```create table events
( id  integer  not null primary key
, datetime_start  datetime not null
, datetime_end    datetime not null
);
insert into events values
( 1, '2006-09-09 14:00', '2006-09-09 16:00' )
,( 2, '2006-09-10 09:00', '2006-09-10 17:00' )
,( 3, '2006-09-11 13:30', '2006-09-11 14:45' )
,( 4, '2006-09-12 09:00', '2006-09-15 17:00' );```

As with any good set of test data, we should be able to work out the correct answer ourselves, ahead of time, and then try to come up with the SQL that will reproduce it. So, using good old paper and pencil, or a spreadsheet if desired, we construct the following:

```1. 0 days 2 hours 0 minutes =  120 minutes
2. 0 days 8 hours 0 minutes =  480 minutes
3. 0 days 1 hour 15 minutes =   75 minutes
4. 3 days 8 hours 0 minutes = 4800 minutes
----
total   5475 minutes
average  1368.75 minutes
=  22 hours 48.75 minutes ```

Now to produce the same results with SQL. First, we need to compute the difference between the start and end. Many database systems actually allow the use of ordinary arithmetic with datetimes (for example, SELECT somedatecol + 1 usually gives the next day), so let's try subtracting:

```select id
, datetime_start
, datetime_end
, datetime_end - datetime_start as diff
from events```

Here's what we get for this query in MySQL:

```id datetime_start    datetime_end         diff
1  2006-09-09 14:00  2006-09-09 16:00    20000
2  2006-09-10 09:00  2006-09-10 17:00    80000
3  2006-09-11 13:30  2006-09-11 14:45    11500
4  2006-09-12 09:00  2006-09-15 17:00  3080000```

And here's what we get in SQL Server:

```id datetime_start    datetime_end      diff
1  2006-09-09 14:00  2006-09-09 16:00  1900-01-01 02:00
2  2006-09-10 09:00  2006-09-10 17:00  1900-01-01 08:00
3  2006-09-11 13:30  2006-09-11 14:45  1900-01-01 01:15
4  2006-09-12 09:00  2006-09-15 17:00  1900-01-04 08:00```

Weird, eh? In MySQL, we get a "formatted" integer, and in SQL Server, we get a new (albeit ancient) datetime value. But can we average these differences?

```select avg(
datetime_end - datetime_start
) as avg_diff
from events```

In MySQL we get 797875, which is clearly wrong. In SQL Server, we get "Operand data type datetime is invalid for avg operator."

What does this imply? Simply that when using an aggregate function like AVG(), we must ensure that we are actually aggregating something meaningful.

One solution is to convert each interval to a numerical "common denominator" as we did with the spreadsheet data. This may be easier in some database systems than others. As always, the trick is to know your functions and pick the appropriate ones. Here, for example, is the MySQL solution:

```select sec_to_time(
avg(
unix_timestamp(datetime_end)
- unix_timestamp(datetime_start)
) ) as avg_diff
from events

avg_diff
22:48:45 ```

We'll leave the solution for SQL Server, and other database systems, as an EFTS (exercise for the student). Good luck!

This was last published in July 2006

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

SearchDataManagement

• Hyperledger Fabric offers path to enterprise blockchain future

Blockchain arose from bitcoin, but it's looking to find a place in the enterprise. Frameworks like Hyperledger Fabric could ...

• MongoDB 4.0 takes ACID transactions to multi-document level

MongoDB is taking a deeper step into SQL-style processing waters with a 4.0 update that brings increased support for ...

• Data lake concept needs firm hand to pay big data dividends

Data lakes pose technology deployment and data management challenges that can leave analytics users high and dry if the ...

• AI functionality limited today but could be a game-changer

Limited AI capabilities could soon give way to technology that is truly transformative for enterprises, surpassing the overhyped ...

SearchSAP

• ControlPanelGRC app eases Steelcase's compliance pain

When Steelcase's SAP environment grew in size and complexity, it turned to Symmetry ControlPanelGRC to save time, have more ...

• Translytical data platforms emerge with SAP HANA as a leader

SAP HANA is a leading translytical platform, according to Forrester, and consulting firm Convergent IS says the combination of ...

• SAP HANA and Esri combine for geospatial database platform

SAP and Esri are combining SAP HANA's in-memory database capabilities with Esri geospatial applications, and utilities are taking...

SearchSQLServer

SQL Operations Studio simplifies routine administration of SQL Server and Azure SQL databases, making database development and ...

• Meltdown and Spectre fixes eyed for SQL Server performance issues

Microsoft has responded to the Spectre and Meltdown chip vulnerabilities with patches and other fixes. But IT teams need to sort ...

• Five SQL Server maintenance steps you should take -- ASAP

Putting off SQL Server administration tasks can lead to database problems. Enact these often-neglected maintenance items to help ...

TheServerSide.com

• Pluralsight IQ, Stack Overflow boost developer street cred

Tying the Pluralsight IQ skills test to the Stack Overflow Developer Story helps developers measure their technical skills and ...

• Why this quantum computing breakthrough is a security risk

Quantum computing will void pretty much all security encryption techniques and open the door to hackers. Here's how to protect ...

• Database automation drives DevOps into the persistence layer

A new breed of software tools is driving DevOps processes deep into the persistence layer, as database automation and continuous ...

SearchDataCenter

• Evaluate read-intensive and write-intensive SSD use cases

Consider write wear, performance and other factors when choosing between read-intensive, write-intensive and mixed-use ...

• Some hyper-converged infrastructure use cases pose pitfalls

Hyper-converged infrastructure adoption is skyrocketing, but that doesn't mean that the technology is the best choice for every ...

• Dell hyper-converged reorg streamlines products, ups CI odds

Market pressures and manufacturing synergies drove Dell to integrate its HCI and CI products with its core business units, but ...

SearchContentManagement

• Content management in the cloud a main theme in 2018

The future of content management resides in the cloud and with AI, as several 2018 conferences will assure you.

• Six things to know about today's SharePoint implementations

As companies migrate their on-premises Microsoft SharePoint sites to the cloud, here are some things they should know about the ...

• Upgrades for the SharePoint Online portal

As more organizations migrate SharePoint sites to the cloud, Microsoft has increased at-a-glance dashboard data and analytics to ...

SearchHRSoftware

• Don't overlook the many benefits of Microsoft Excel for HR

The maligned spreadsheet tool is no substitute for enterprise apps like HRMS and people analytics, but it will do in a pinch and ...

• HR is failing to use people analytics tools, new report says

Human resource departments fail to use people analytics tools effectively, a new global study concludes. The findings were called...

• Does your company need new human resource management tools?

Finding the best human resource management tools starts with identifying your company's present and future needs, before ...

Close