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!

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

• MariaDB X4 brings smart transactions to open source database

Open source database vendor MariaDB updates its flagship platform with new features to enable the convergence of transactional ...

• How data lineage tools boost data governance policies

Organizations can bolster data governance efforts by tracking the lineage of data in their systems. Get advice on how to do so ...

• Proactive practices for data quality improvement

Instead of waiting for data quality to become an issue, consider a proactive approach. Here are some ways to improve data quality...

• Storytelling using data makes information easy to digest

In a Q&A, Nate Nichols and Anna Schena Walsh of AI-based analytics vendor Narrative Science talk about how data storytelling can ...

• Data-driven storytelling makes data accessible

In a Q&A, Nate Nichols and Anna Schena Walsh of data storytelling vendor Narrative Science discuss their book on storytelling and...

• Startup Uplevel targets software engineering efficiency

Startup vendor Uplevel emerged from stealth on Wednesday touting a platform aimed at improving the efficiency of software ...

SearchSAP

• SAP S/4HANA migration: Critical advice for moving off ECC

With the end of SAP ECC support looming in 2025, organizations must make some tough decisions. Here's a look at your choices.

• New SAP leadership faces big challenges in 2020

Industry analysts discuss SAP's biggest issues in 2020, including how the two new CEOs will guide the company deeper into the ...

• SAP Data Hub opens predictive possibilities at Paul Hartmann

When medical supply firm Paul Hartmann AG tested a supply chain analysis system built on SAP Data Hub, it found that it could ...

SearchSQLServer

• SQL Server database design best practices and tips for DBAs

Good database design is a must to meet processing needs in SQL Server systems. In a webinar, consultant Koen Verbeeck offered ...

• SQL Server in Azure database choices and what they offer users

SQL Server databases can be moved to the Azure cloud in several different ways. Here's what you'll get from each of the options ...

• Using a LEFT OUTER JOIN vs. RIGHT OUTER JOIN in SQL

In this book excerpt, you'll learn LEFT OUTER JOIN vs. RIGHT OUTER JOIN techniques and find various examples for creating SQL ...

TheServerSide.com

• Don't ever put a non-Java LTS release into production

Development teams should avoid non-long-term support releases at all costs. Pay attention to the Java release cycle to make sure ...

• Public API strategy considerations for enterprise adoption

As organizations look for more cost-effective ways to manage data, an evolving landscape with APIs has made the technology more ...

• Ideas on how to hold a successful code hackathon

Want to host a hackathon? Here are some ideas on what a company can do to host an event that solves problems and reenergizes the ...

SearchDataCenter

• Organizations try to predict the effect of 5G infrastructure

With more 5G and IoT devices emerging, admins must prepare their data centers to support low-latency apps and edge computing with...

• Top infrastructure and operations technology myths of 2019

Admins are consistently evaluating technology to improve I&O efficiency. Cost, integration and business goals are key components ...

• Improve efficiency with server energy consumption tools

Deciding what servers are most efficient for your infrastructure requires research. Hardware-level certifications and web-based ...

SearchContentManagement

• Ex-SAP exec steers Episerver CMS toward digital experience market

Alex Atzberger discusses leaving the helm of SAP's CX platform to become Episerver CEO. Now, Episerver looks to reinvent itself ...

• 4 digital transformation terms to know

As technology evolves, businesses have no choice but to follow. Digital transformations are inevitable in order to keep customers...

• How to differentiate between CX and DX platforms

CX and DX platforms have similarities in how they manage content to produce interactive experiences, but they aren't the same. ...

SearchHRSoftware

• Top 7 HR trends for 2020 and beyond: The change decade

Because HR requires a balance between the needs of the organization with the needs of employees, it's always been a balancing act...

• For insider threat programs, HR should provide checks and balances

Insider threat programs may backfire if employees feel they are intrusive and violate privacy, Forrester Research warns. Making ...

• Better HR security could help thwart Iranian cyberattack

HR departments have a broad role to help protect their firms from Iranian cyberattacks. The security efforts include helping with...

Close