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

# GROUP BY with two tables, part 1

I want the sum of two columns from two different tables -- one column from each table. When I write a simple query like...

```SELECT    p.ddate
,         SUM (p.ddblock)
,         SUM (l.gtblock)
FROM      permit      p
,         localpwblk  l
GROUP BY  p.ddate;
```

... I received a wrong answer. (The sum from table p is multiplied by the number of records in table l and vice versa.)
I created some sample data; four rows in table "permit" and two rows in "localpwblk".

When you run a query with an aggregate function (like "SUM base_column_x)"), SQL first runs the corresponding query that includes each base_column. So in your example, SQL first runs this query:

```SELECT    p.ddate
,         p.ddblock
,         l.gtblock
FROM      permit      p
,         localpwblk  l;

DDATE          DDBLOCK    GTBLOCK
----------- ---------- ----------
21-Mar-2004         10        300
22-Mar-2004         20        300
22-Mar-2004         30        300
22-Mar-2004         40        300
21-Mar-2004         10        400
22-Mar-2004         20        400
22-Mar-2004         30        400
22-Mar-2004         40        400
```

Since you didn't specify any join condition between the two tables, SQL does a cross-join; that is, every row in each table is joined to every row in the other. SQL then computes the aggregates you requested, for the groups you specified, from that result set.

That explains what SQL is doing. How do you get SQL to do what you want? That depends on what you want, which you never mentioned. Apparently, you want a subtotal for each ddate from "permit", and something from "localpwblk". I'll make two guesses what that something is:

1. The grand total: That is, you want the same figure from "localpwblk" repeated on each line of output.
2. A correlated sub-total: That is, the figure from "localpwblk" may vary for each group. For example, you may want a daily total for the same day.

In either case, the elegant solution involves an in-line view, that is, a result set from a sub-query that is itself queried like a table. In-line views (new in Oracle 8) make dealing with GROUP BY and joins much, much easier. Whenever you have a problem with a GROUP BY and two or more tables, you should immediately think of in-line views.

If you are using Oracle 9 (or above), you can also use a scalar sub-query, a sub-query that returns one column and (at most) one row, that behaves like a columnin any other table.

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

• ### Top database cloud migration considerations for enterprises

As the amount of incoming data grows, many organizations are switching to cloud databases. Understanding what database best meets...

• ### Amazon cloud database and data analytics expand

AWS expands its Redshift data warehouse capabilities including managed storage and query acceleration at the re:Invent 2019 ...

• ### Vendors move away from open source database software licensing

While open source is a key to success for many database vendors, it can also potentially lead to a competitive threat from a ...

• ### BI vendors jump into low-code/no-code tools for developers

A spate of BI vendors included easy-to-use tools for developers in their recent updates, perhaps marking the start of a new trend...

• ### Sisense analytics platform update features AI, data prep tool

Augmented intelligence features and an in-warehouse data prep tool highlight Sisense's latest update, its second since acquiring ...

• ### Operation Fistula uses data to treat childbirth injuries

Aided by an analytics stack developed by Exasol, nonprofit Operation Fistula is working to end obstetric fistula in targeted ...

## SearchSAP

• ### Partners need to target SAP SMB market for cloud transition

In this Q&A, SAP executive Claus Gruenewald discusses how SAP partners are instrumental in servicing the SMB market and how they ...

• ### S/4HANA Cloud integrates Qualtrics for continuous improvement

The latest version of SAP S/4HANA Cloud embeds Qualtrics XM capabilities that provide a way for users to give direct feedback ...

• ### SAP Data Warehouse Cloud may democratize data analytics

SAP's new SAP Data Warehouse Cloud promises to make data analytics more accessible to the business. It's a needed addition to ...

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

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

• ### A Jenkins tutorial for beginners with examples

If you're ready to try Jenkins, this quick start tutorial lays out the specific steps you'll need to take to download and install...

## SearchDataCenter

• ### Top 4 open source automation tools for admins

Open source offerings are an easy way to bring automation into your organization. When selecting software, evaluate the user ...

• ### U.S. facility may have best data center PUE

The data center energy efficiency metric, power usage effectiveness, or PUE, is not improving. But one supercomputer data center ...

• ### Increase efficiency with data center temperature monitoring

Data centers must track multiple temperature components. Organizations can use ASHRAE standards and on-premises hardware for ...

## SearchContentManagement

• ### New capabilities added to Alfresco Governance Services

The updates are intended to secure electronically stored information residing across different locations in light of recent ...

• ### Top 5 Office 365 skills for SharePoint administrators

Microsoft SharePoint administrators need to branch out in their Office 365 skill set to support products tightly integrating with...

• ### Box cloud content management helps simplify digital work

Box currently has three main areas of focus: integration with enterprise applications, content security and collaboration. The ...

## SearchHRSoftware

• ### As hiring booms, HR survey raises warning for recruiters

Job candidates will reject a job offer if the employer makes missteps in the recruiting process, a new HR survey reports.

• ### IT's technology experience problem gets HR tool

Technology deployments have been blamed for loss of productivity and even employee resignations. A new tool from Qualtrics could ...

• ### 3 keys to employee engagement measurement

Far too many organizations and their HR departments conduct employee engagement measurement in a way that does more harm than ...

Close