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

# 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

• ### Apache Hadoop 3.0 goes GA, adds hooks for cloud and GPUs

Is this the post-Hadoop era? Not in the eyes of Hadoop 3.0 backers, who see the latest update to the big data framework ...

• ### Expert: For BI, you must know the data integration process

Understanding the data integration process is central to self-service BI and data architecture design, consultant Rick Sherman ...

• ### Graph technology rivals take Amazon Neptune database in stride

Amazon's Neptune database may change the status quo in the graph technology world. But it could also introduce a wider base of ...

• ### Predictive analytics projects can bolster business decisions

Blind faith in predictive models can result in flawed business decisions. Analytics teams need to manage predictive processes ...

• ### How predictive analytics techniques and processes work

Predictive analytics is no longer confined to data scientists and other highly skilled analysts. But other users need to ...

• ### Hyper engine aims to give enterprise Tableau analytics a boost

The Hyper in-memory data engine added in Tableau 10.5 could make Tableau analytics capabilities more expansive, enabling the ...

## SearchSAP

• ### SAP S/4HANA Cloud and indirect access will dominate 2018

Industry experts say SAP S/4HANA Cloud migrations, Leonardo and Cloud Platform are the technology issues for SAP in 2018; on the ...

When a Dutch energy grid provider needed to develop new business apps on top of SAP ERP, it turned to the Mendix RAD platform to ...

• ### SAP's Timo Elliott on enterprise chatbot AI technology

The SAP global innovation evangelist expects AI to affect businesses in three ways: human-computer interaction, automation of ...

## SearchSQLServer

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

• ### Microsoft Cosmos DB takes Azure databases to a higher level

Azure Cosmos DB brings a new element to the database lineup of Microsoft's cloud platform, offering multiple data models and a ...

## TheServerSide.com

• ### Spring creator Rod Johnson releases API for implementing DevOps

Find out about Rod Johnson's latest project, which promises to simplify the process of implementing DevOps and streamlining the ...

• ### What Java developers need to know about TypeScript syntax

For Java developers transitioning into JavaScript frameworks, like React and Angular, this TypeScript tutorial on syntax will ...

• ### AWS Cloud9 IDE threatens Microsoft developer base

With its Cloud9 IDE, AWS challenges Microsoft where it matters most -- with the developer community, where Microsoft has ...

## SearchDataCenter

• ### Three requirements for a hybrid cloud computing deployment

As the hybrid cloud computing approach gains steam, organizations will need to pay close attention to cross-cloud connectivity ...

• ### Five debunked myths about SSD issues

Solid-state drives are mature now, and the technology has eclipsed hard disk drives with superior performance, manageability and ...

• ### Future data center trends hinge on the edge, cloud and staffing

Edge computing, colocation, cloud and IT staffing issues lead the way as industry analysts make their predictions for the future ...

## SearchContentManagement

• ### Intelligent information management the next wave for ECM

In a 2018 upgrade, M-Files allows users to search for content in multiple repositories, while also being able to automatically ...

• ### SharePoint integration and implementation best practices

Here are some expert advice and tips, as well common definitions, to help make your SharePoint integration and implementation a ...

• ### SharePoint branding capabilities get a facelift

Since Microsoft Ignite last September, SharePoint Online is getting new branding capabilities that have been on the wish lists of...

## SearchFinancialApplications

• ### Finance IT case study: Reporting secrets of Derek Rose

CEO Sacha Rose says specialist reporting tools have saved the company thousands by avoiding unnecessary mistakes.

• ### WestJet turns to gamification to help its Oracle ERP users soar

WestJet's initial gamification project focuses on expense reporting.

• ### The Transformation of HR is Underway

HR is being transformed while we watch.

Close