Q

# Averages over a span of years -- Part 1

For the following sample relation:

```subject | year | enrolled ----------+---------+------------- subject1 | 1998 | 20 subject1 | 1999 | 23 subject1 | 2000 | 16 subject2 | 1999 | 10 subject2 | 2000 | 21 subject3 | 2000 | 9
```

How would I create a query that calculates the average enrollment for each subject over the years? Thanks!

The answer depends on what is meant by an average "over the years."

Here's a solution involving a straightforward average calculation, using the AVG function:

```select subject , avg(enrolled) as avgamt from subjects group by subject
subject avgamt subject1 19.67 subject2 15.50 subject3 9.00
```

Everything looks okay, right? Each subject has one or more entries in the table, and the average was calculated as the sum per subject divided by the number of rows, right?

But what if the average needs to be calculated over all years in the span of years from 1998 to 2000? How do we deal with the fact that some subjects are missing some years?

What we could do is supply the missing years for each subject. There's more than one way to do this, but here's a simple one. The following query uses the integers table (described in Finding all the dates between two dates, 10 June 2002, and also in Aggregates for date ranges, 4 October 2002). The integers table is joined with the original table in a cross join to generate the desired range of years for each subject:

```select distinct subject , 1998+i as theyear from integers , subjects where i between 0 and 2
subject theyear subject1 1998 subject1 1999 subject1 2000 subject2 1998 subject2 1999 subject2 2000 subject3 1998 subject3 1999 subject3 2000
```

How did we know to use "1998+i" and "i between 0 and 2" in this query? By inspection. Actually, in the general case, inspection would not be used, and instead, additional subqueries would obtain the lowest and highest years from the sample data.

We can now use the results of this cross join as a derived table and join it to the original table. We want to use a left outer join, since we know some rows will not match:

```select allyears.subject , allyears.theyear , enrolled from ( select distinct subject , 1998+i as theyear from integers , subjects where i between 0 and 2 ) as allyears left outer join subjects on allyears.subject = subjects.subject and allyears.theyear = subjects.theyear order by allyears.subject , allyears.theyear
subject theyear enrolled subject1 1998 20 subject1 1999 23 subject1 2000 16 subject2 1998 - subject2 1999 10 subject2 2000 21 subject3 1998 - subject3 1999 - subject3 2000 9
```

Okay, that looks fine. So let's try the averages again:

```select allyears.subject , avg(enrolled) as avgamt from ( select distinct subject , 1998+i as theyear from integers , subjects where i between 0 and 2 ) as allyears left outer join subjects on allyears.subject = subjects.subject and allyears.theyear = subjects.theyear group by allyears.subject
subject avgamt subject1 19.67 subject2 15.50 subject3 9.00
```

Uh oh. These are our original results. How can this be?

The explanation is that aggregate functions exclude NULLs. Please see Part 2 of this answer for more information on working with NULLs and aggregates.

This was last published in November 2002

## 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

• ### Cross-platform integration, data preparation process grows in cloud

While cloud computing may be convenient and more cost-effective for users, it can also lead to new challenges and requirements in...

• ### Graph data model cements tight relationships between data elements

Graph databases can help define and discover relationships between entities -- and offer increased flexibility and better ...

• ### Microsoft SQL Server 2016 relational DBMS overview

Microsoft SQL Server 2016 for Windows comes in four editions, with updates that include a new stretch database feature, Polybase,...

• ### Difficulties in hiring data scientists can waylay analytics efforts

Advanced analytics software provides a lot of functionality, but finding skilled data scientists who can use the available tools ...

• ### Creative projects leave people guessing about future impact of AI

A push is underway to write creative AI algorithms that can engage in music, film and design projects. So far, they have ...

## SearchSAP

• ### Hillarys Blinds speeds SAP S/4HANA upgrade with Panaya tool

Hillarys Blinds, a veteran of several SAP ECC upgrades, completed a move to SAP S/4HANA in just six months using the Panaya ...

• ### Charlotte Hornets build data warehouse with SAP HANA-based Phizzle

The Charlotte Hornets implemented Phizzle FanTracker, an SAP HANA-based platform, to consolidate fan records from many data ...

• ### Does SAP ONE Support Launchpad make SAP support any easier to use?

The new Fiori user experience makes it easier to access applications and support services, but product-specific support still ...

## SearchSQLServer

• ### SQL Server on Linux signals Microsoft's changing development landscape

Expert Joey D'Antoni explains what SQL Server on Linux and the addition of Enterprise Edition features to Standard Edition say ...

• ### How to get the most out of virtual SQL Server with Microsoft Hyper-V

SQL Server is a CPU-intensive technology, which can make it tricky to run in a virtualized environment. Keep your SQL Server ...

• ### Microsoft previews SQL Server on Linux, opens features across editions

Microsoft looks to broaden the horizons of SQL Server, as it moves some Enterprise features to Standard Edition and issues the ...

## TheServerSide

• ### Docker instances become the new norm and adoption goes mainstream

Many organizations use Docker instances for many reasons, although security, data storage and monolithic fears remain barriers to...

• ### How to turn your DevOps failures into ALM successes

Doing the right thing doesn't always mean you're doing things right. But don't fret, because short-term DevOps failures can mean ...

• ### From chatbots to IBM's Watson: How software deals with conversational language

The next big thing in software development is conquering the conversational language development hurdle. Here's how the big ...

## SearchDataCenter

• ### Build a data center shutdown procedure to prepare for the worst

A data center shutdown checklist helps IT teams focus on backup, testing and system verification before pulling the plug and ...

• ### Telcos purge colocation data centers, open door to neutral connections

Enterprise customers in Verizon and CenturyLink's colocation data centers should expect better cloud and network connection ...

• ### IT slowly embraces composable infrastructure

If there will be a way to make an enterprise data center as efficient and optimized as cloud computing, composable infrastructure...

## SearchContentManagement

• ### Microsoft brings its flavor of AI with Microsoft Cognitive Services

Microsoft Cognitive Services has a new array of APIs to make it easier to scan text, video and audio data and to bring ...

• ### Users prefer Office 365 suite collaboration features over SharePoint

Users don't want to jump through hoops, and they want applications to work on mobile devices. Those needs may kill traditional ...

• ### What new SharePoint features to expect in the next 12 months

Now that Microsoft is developing its SharePoint features, there are new feature rollouts all the time. Here's a rundown of the ...

## SearchFinancialApplications

• ### Foot Locker seeks a good fit with Infor pre-employment assessment tool

Foot Locker is among a growing number of companies using cloud-based pre-hire assessment to screen job applicants for character ...

• ### Project planning for a new corporate performance management system

A corporate performance management system touches most aspects of any business. You need a carefully thought-out plan to ensure a...

• ### No one-size-fits-all strategy for cloud ERP software migration

Experts say a cloud ERP transition plan will vary according to a variety of factors, from company size to an organization's ...

Close