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

Counts from two different tables in one query

Based on these entities:

```EMPLOYEE
FNAME
LNAME
SSN          PK
DNO              FK to DEPARTMENT.DNUMBER

DEPARTMENT
DNAME
DNUMBER      PK
MGRSTARTDATE

DEPT_LOCATIONS

DNUMBER      PK, FK to DEPARTMENT.DNUMBER
DLOCATION    PK```

How would I write this query in SQL:

"For each department with more than one location, retrieve the department's name, department number, and the number of employees who work for the department."

The first count we want is for departments with more than one location. We don't actually want the count itself, we just need to use it in the HAVING clause when we GROUP BY department:

```select dnumber
from dept_locations
group
by dnumber
having count(*) > 1 ```

The second count is for each department, where we need the count of its employees. For this, we need to join the department and employee tables, and use GROUP BY again, but this time, it's the employee rows that are being counted:

```select dname
, dnumber
, count(employees.dno)
from department
left outer
join employees
on department.dnumber = employees.dno
group
by dname
, dnumber ```

Note that a LEFT OUTER JOIN is used, so that we get a count for all departments, including any with no employees. If a department has no employees, count(employees.dno) will be 0, while count(*) would be 1, because even if a department has no employees, there's still a row for it in the result set (in other words, each group in an outer join has at least one row).

Finally, we incorporate the first query as a subquery in the second, so that it qualifies which departments we're interested in:

```select dname
, dnumber
, count(employees.dno)
from department
left outer
join employees
on department.dnumber = employees.dno
where dnumber in
( select dnumber
from dept_locations
group by dnumber
having count(*) > 1  )
group
by dname
, dnumber ```

Since the subquery is not correlated, the database can execute it ahead of the main query, and simply "feed" the main query a list of department numbers in the WHERE clause.

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

• Amazon Quantum Ledger Database brings immutable transactions

Based on technology built internally at Amazon, the tech giant's newest database provides a centralized approach for enabling a ...

• Stibo Systems advances multidomain MDM system

The new Stibo Systems 9.2 update expands the MDM platform's features with Sisense business intelligence integration and machine ...

• Cloudera Data Platform to debut, as big data fortunes waver

The interim CEO of Cloudera is cautiously optimistic about growth prospects as the big data vendor acquired Arcadia Data and ...

• Oracle BI platform on the comeback trail

Time had seemingly left Oracle's business intelligence tools behind -- until the vendor responded by consolidating its BI ...

• BI for mobile remains a challenge for vendors

While some BI vendors have developed effective mobile apps that provide concise insights, those that have attempted to recreate ...

• Magento BI update a benefit to vendor's e-commerce customers

Magento rolled out the Magento Business Intelligence Summer 2019 Release, updating its BI platform with enhanced scheduling ...

SearchSAP

• Navy sails SAP ERP systems to AWS GovCloud

The Navy consolidated 26 various ERP systems onto SAP HANA on the AWS GovCloud, leading to data reduction, lower TCO, and setting...

• SAP HANA application collects concussion data for real-time analysis

Protecht, an SAP HANA based system, enables teams in contact sports to measure and analyze data about hits though an IoT sensor ...

• S/4HANA public cloud vs. private cloud: Compare the pros, cons

In addition to SAP's on-premises and hybrid models, the vendor offers S/4HANA in public and private clouds. Here's a look at the ...

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

• Eclipse completes enterprise Java move with Jakarta EE 8

The Eclipse Foundation has assumed control of the Java EE enterprise platform and specifications from Oracle and has launched an ...

• AI development tools make software development easier

Software tools with AI can help optimize various elements to make the development pipeline easier to handle for all those ...

• Close Agile open source tools vulnerabilities

The State of the Software Supply Chain report highlights some developer team best practices to help increase productivity with ...

SearchDataCenter

• IBM z15 mainframe secures data across multi-cloud environments

IBM unveiled the latest in its line of mainframes capable of processing 1 trillion web transactions a day. The IBM z15 ...

• Data center management as a service launches DCIM to the cloud

DMaaS is an option for organizations that want to use cloud-based management. Though these offerings hold a lot of promise, there...

• Decrease legacy hardware security gaps

Dated infrastructure poses security threats to organizations -- especially with the amount of sensitive data used today. Address ...

SearchContentManagement

• Cohesion is latest Acquia acquisition

While Acquia would not provide specifics of the deal, the decision behind the acquisition of Cohesion was the chance to bring ...

• 3 things to learn before considering blockchain integration

Paul Swider, CTO at RealActivity LLC, discusses how to use blockchain technology to increase the security and usefulness of ...

• Microsoft PowerApps pricing proposal puts users on edge

Microsoft's PowerApps pricing changes, expected to take effect in October, could make them too expensive for some users who ...

SearchHRSoftware

• HiQ Labs vs LinkedIn case OKs robot monitoring of employees

A U.S. Court of Appeals ruled on the LinkedIn vs HiQ lawsuit, which could help shape how services gather information on social ...

• MyPayrollHR collapse stirs allegations, questions, anger

The problems created by the closing of MyPayrollHR may take a long time to resolve. The FBI has been contacted and lawsuits are ...

• Before deploying recruitment chatbots, define use cases

HR departments can benefit from using chatbots for basic tasks, but the technology will eventually be able to handle more complex...

Close