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

# Detail rows for accounts that occur three times

## Our SQL expert answers a tough query using both the IN subquery and derived tables.

I have a table with weekly data:
```    WeekEnding   Amt   Acct
----------  ----   ----
2007-10-06  5.00   XYZ
2007-10-13  3.00   XYZ
2007-10-20  0.23   XYZ
2007-10-06  5.00   ZZZ
2007-10-13  0.23   ZZZ
```
I want all of the accounts and amounts for accounts that occur in at least three different week ending dates. Can you help?

The difficulty with this type of problem is that it requires returning detail rows for a situation which is easily solved with HAVING. However, to use HAVING we have to use GROUP BY, and then the detail rows are aggregated. The way to approach this problem is to break it down into components. The first component of the solution does involve the HAVING clause.

```select Acct
from Weekly
group
by Acct
having count(*) >= 3```

Note that COUNT(DISTINCT WeekEnding) also works. Whether we use this or the simpler COUNT(*) depends on whether the combination of WeekEnding and Acct is unique. Counting distinct values may be necessary if, for example, there are other columns you didn't mention, such as customer. In that case, we might have one row per customer per account per week ending date, so COUNT(DISTINCT WeekEnding) is necessary if the GROUP BY is only on the account.

Now that we know which accounts qualify, we can build the other component, which is the selection of all detail rows for the accounts which qualify. This can be accomplished in two ways. The first method uses an IN subquery:

```select WeekEnding
, Amt
, Acct
from Weekly
where Acct in
( select Acct
from Weekly
group
by Acct
having count(*) >= 3 )```

The second method uses the same subquery but as a derived table in the FROM clause:

```select WeekEnding
, Amt
, Acct
from Weekly
inner
join ( select Acct
from Weekly
group
by Acct
having count(*) >= 3 ) as ok_accts
on ok_accts.Acct = Weekly.Acct```

What is the difference between these two solutions? As far as execution goes, they should perform the same. But the derived table has an advantage. Suppose that if, instead of one column, the HAVING condition needed to be based on a GROUP BY involving two columns. What if you wanted details for all customer accounts that occurred at least 3 times?

The first solution would be:

```select WeekEnding
, Amt
, Acct
, Customer
from Weekly
where ( Acct, Customer ) in
( select Acct
, Customer
from Weekly
group
by Acct
, Customer
having count(*) >= 3 )```

This solution now uses what is called a row constructor, and this is perfectly valid SQL. The problem with row constructors is that not every database engine supports them. Yet.

Now imagine what the query involving the join to the derived table would look like.

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