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?

## SearchDataManagement

• ### Era Software raises \$15.25M for enterprise data management

Startup that began as the EraDB time series database is advancing its efforts with new funding and a cloud service for its ...

• ### Dgraph GraphQL database users detail graph use cases

Graph DB vendor Dgraph Labs is expanding its AWS cloud footprint with new regions and adding change data capture capabilities in ...

• ### Pandemic triggered data security movement to DBaaS

Database-as-a-service technology has aided enterprises tasked with keeping data secure with IT professionals working from home ...

• ### Startup Veezoo emerges from stealth with NLQ-based platform

Aiming to be 'Siri for enterprises,' an analytics startup emerged from stealth with a platform that enables users to interact ...

• ### 15 data science tools to consider using in 2021

Numerous tools are available for data science applications. Read about 15, including their features, capabilities and uses, to ...

• ### Insightsoftware acquisition of Izenda targets embedded BI

ERP vendor Insightsoftware acquired embedded analytics specialist Izenda on April 15, marking its second purchase of an embedded ...

## SearchSAP

• ### S/4HANA Cloud SaaS ERP: Buying team overview

SAP's multi-tenant SaaS ERP, S/4HANA Cloud, is a viable choice for companies that need ease in their infrastructure management. ...

• ### SAP forms financial services partnership with Dediq

SAP and financial industry investment firm Dediq are forming a new business unit to develop applications that help banks and ...

• ### Unpatched applications threaten SAP security

Cyberattacks are a significant threat to unpatched, unprotected SAP applications, according to a new threat intelligence report ...

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

• ### Incorporate diversity and inclusion in technology design

DEI in technology is about more than creating a diverse workplace. We talked to a few DEI professionals about how teams build ...

• ### Microsoft previews OpenJDK distro to the delight of devs

In a move meant to attract more Java developers to its Azure cloud and further support the Java community, Microsoft launched a ...

• ### Supreme Court ruling on Java APIs eases developer worries

Now that the Supreme Court has ruled for Google over Oracle in their high-stakes copyright battle over Java APIs, developers can ...

## SearchDataCenter

• ### Nvidia SDK simulates quantum computing circuits on GPU systems

Nvidia edged its way into the quantum computing market with an SDK that simulates quantum circuits by adding horsepower to ...

• ### Programmable processor technology for next-gen data centers

The right processing technology can benefit your data center. Learn about advancements in CPU technologies, recent vendor ...

• ### Data processing units accelerate infrastructure performance

DPUs often run on networking packets to move information in the data center, instead of supporting processing workflows. Get an ...

## SearchContentManagement

• ### OpenText releases Cloud Editions content services updates

OpenText CE 21.2 includes federated document compliance that extends to Microsoft Office 365, along with a revamped content ...

As the pandemic disrupts paper workflows, Adobe courts small business users with simple webforms, digital signatures and payments...

• ### Know when to use a headless CMS and when it's not worth it

Headless CMSes aren't a silver bullet for every circumstance. Evaluate three solid use cases for a headless CMS and three ...

## SearchHRSoftware

• ### Face mask detection a newcomer to employee surveillance

Face mask detection has emerged as another form of employee surveillance technology, and its adoption may be helped indirectly by...

• ### 20 diversity and inclusion tools to power your DEI program

Diversity and inclusion tools shouldn't replace strategy, but these tools can help companies in multiple ways, from tracking ...

• ### DEI tools arrive at critical time for HR

Employers are being held accountable for meeting diversity, equity and inclusion goals, especially executives. HR vendors are ...

Close