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

# Top N rows for each X

I want a query for retrieving the top two recently inserted records for each id. My table has columns id, adate, and description. There are five records with id 2 and four records with id 3. I want to retrieve top two records for both id 2 and 3. I should get total four records, two with id 2 and two with id 3.

Consider the following data:

```id  adate     description
2 2005-02-11 1st-of-5
2 2005-02-12 2nd-of-5
2 2005-02-13 3rd-of-5
2 2005-02-14 4th-of-5
2 2005-02-15 5th-of-5
3 2005-03-01 1st-of-4
3 2005-03-02 2nd-of-4
3 2005-03-03 3rd-of-4
3 2005-03-04 4th-of-4```

Now let's set up a theta join. A theta join uses an inequality in the join condition. The join will be a self-join, and each row will be joined to all rows for the same id which have an equal or later date.

```select t1.id
, t1.description
, t2.id
, t2.description
from thetable as t1
inner
join thetable as t2
on t1.id = t2.id
order
by t1.id

The above query produces these results:

``` 2 2005-02-11 1st-of-5   2 2005-02-11 1st-of-5
2 2005-02-11 1st-of-5   2 2005-02-12 2nd-of-5
2 2005-02-11 1st-of-5   2 2005-02-13 3rd-of-5
2 2005-02-11 1st-of-5   2 2005-02-14 4th-of-5
2 2005-02-11 1st-of-5   2 2005-02-15 5th-of-5

2 2005-02-12 2nd-of-5   2 2005-02-12 2nd-of-5
2 2005-02-12 2nd-of-5   2 2005-02-13 3rd-of-5
2 2005-02-12 2nd-of-5   2 2005-02-14 4th-of-5
2 2005-02-12 2nd-of-5   2 2005-02-15 5th-of-5

2 2005-02-13 3rd-of-5   2 2005-02-13 3rd-of-5
2 2005-02-13 3rd-of-5   2 2005-02-14 4th-of-5
2 2005-02-13 3rd-of-5   2 2005-02-15 5th-of-5

2 2005-02-14 4th-of-5   2 2005-02-14 4th-of-5
2 2005-02-14 4th-of-5   2 2005-02-15 5th-of-5

2 2005-02-15 5th-of-5   2 2005-02-15 5th-of-5

3 2005-03-01 1st-of-4   3 2005-03-01 1st-of-4
3 2005-03-01 1st-of-4   3 2005-03-02 2nd-of-4
3 2005-03-01 1st-of-4   3 2005-03-03 3rd-of-4
3 2005-03-01 1st-of-4   3 2005-03-04 4th-of-4

3 2005-03-02 2nd-of-4   3 2005-03-02 2nd-of-4
3 2005-03-02 2nd-of-4   3 2005-03-03 3rd-of-4
3 2005-03-02 2nd-of-4   3 2005-03-04 4th-of-4

3 2005-03-03 3rd-of-4   3 2005-03-03 3rd-of-4
3 2005-03-03 3rd-of-4   3 2005-03-04 4th-of-4

3 2005-03-04 4th-of-4   3 2005-03-04 4th-of-4```

Notice how each row of t1 is joined only to those rows of t2 for the same id where the t2 date is equal or later.

Next, let's change the query so that it counts the number of joined t2 rows instead of displaying them:

```select t1.id
, t1.description
, count(*)
from thetable as t1
inner
join thetable as t2
on t1.id = t2.id
group
by t1.id
, t1.description```

This query produces these results:

``` 2 2005-02-11 1st-of-5  5
2 2005-02-12 2nd-of-5  4
2 2005-02-13 3rd-of-5  3
2 2005-02-14 4th-of-5  2
2 2005-02-15 5th-of-5  1
3 2005-03-01 1st-of-4  4
3 2005-03-02 2nd-of-4  3
3 2005-03-03 3rd-of-4  2
3 2005-03-04 4th-of-4  1```

Now all we have to do is restrict the returned rows based on the count being less than or equal to 2. In other words, we want t1 rows where there are only 1 or 2 t2 rows with a later date.

```select t1.id
, t1.description
from thetable as t1
inner
join thetable as t2
on t1.id = t2.id
group
by t1.id
, t1.description
having count(*) <= 2 ```

This query gives us our final results:

``` 2 2005-02-14 4th-of-5
2 2005-02-15 5th-of-5
3 2005-03-03 3rd-of-4
3 2005-03-04 4th-of-4```

This query will work in all databases, because it doesn't use proprietary syntax like TOP, LIMIT, or ROWNUM.

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