Q

Count consecutive years

I am struggling with writing a query to count consecutive years from the current year. I do not want to use a cursor. There is no requirement for the dates to be 365 days apart, just that they have different years. Any thoughts would be appreciated.

I am struggling with writing a query to count consecutive years from the current year. I do not want to use a cursor....

Our data looks something like this:

```ID  DateCol
1 02/01/2006
1 01/01/2006
1 01/01/2005
1 01/01/2004
1 01/01/1999
2 02/01/2006
2 01/01/2005
3 04/01/2006
3 04/01/1999
4 06/30/2000
4 08/01/1999```

My desired output would be something like this:

```ID ConYears
1    3
2    2
3    1```

There is no requirement for the dates to be 365 days apart, just that they have different years. Any thoughts would be appreciated.

What a nice problem. There are probably ways to do it with just the single table, using a self-join technique similar to the one described in Gaps in sequences (9 February 2004). However, this could get complicated, because you said "consecutive years from the current year" and the first gap could be the current year, which the self-join wouldn't know of.

Once again we can use the handy-dandy integers table to help. If you don't have an integers table, you should; it's small, efficient and very useful.

```create table integers
(i integer not null )

insert into integers values
(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)```

The integers table can then be used to generate the last 10 years:

```select year(current_date) - i as yr
from integers

yr
2006
2005
2004
2003
2002
2001
2000
1999
1998
1997```

The solution uses a CROSS JOIN and a LEFT OUTER JOIN. The CROSS JOIN creates all possible combinations of ID and year. Then the LEFT OUTER JOIN attempts to match each such ID and year combination to a row in the data table.

```select X.ID
, max(X.yr) as FirstMissing
, year(current_date)
-max(X.yr) as ConYears
from (
select ID
, year(current_date) - i as yr
from integers
cross
join (
select distinct ID
from datatable
) as I
) as X
left outer
join datatable as T
on T.ID = X.ID
and year(T.DateCol) = X.yr
where T.ID is null
group
by X.ID
having year(current_date)
-max(X.yr)          > 0```

The derived table called X contains each combination of ID and year. This is the left table in the outer join, and it is joined to the data table, such that it matches the ID and year of the data. Note that it doesn't matter if more than one row of the data table matches, as is the case in your original data for ID 1 and year 2006.

Where a matching row is not found, using the IS NULL condition in the WHERE clause, that combination of ID and year is retained (matching rows are filtered out), and then, using a GROUP BY, only the maximum year which was not found for each ID is chosen, and the number of consecutive years calculated for each ID. Finally, the HAVING clause rejects any IDs like 4 which had 0 consecutive years from the current year.

```ID FirstMissing ConYears
1      2003        3
2      2004        2
3      2005        1```

Pretty neat, eh?

This was last published in January 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

• 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