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

• ### ArangoDB 3.5 update improves multi-model database platform

ArangoDB 3.5 accelerates its database platform with improved query performance and enhanced data security capabilities, as market...

• ### GDPR, AI intensify privacy and data protection compliance demands

This guide covers the challenges data management teams face on data protection and privacy, particularly with the rise of GDPR ...

• ### SnapLogic boosts its data integration technology with AI

SnapLogic's latest update for its Intelligent Integration Platform aims to make it easier for users to benefit from data ...

• ### 5 augmented analytics examples in the enterprise

Here are the top examples of augmented analytics uses that BI vendors support and enable, including data preparation, NLP-based ...

• ### Phocas BI tool proves its value for manufacturers, wholesalers

With its focus on the manufacturing and wholesale distribution industries, Phocas Software has carved out a niche for itself ...

• ### The Salesforce acquisition of Tableau complements Einstein Analytics

Given the different strengths of Salesforce's Einstein Analytics platform and Tableau, the BI tools could prove complementary now...

## SearchSAP

• ### SAP S/4HANA Cloud 1908 gets more RPA, embedded analytics

The quarterly release of SAP S/4HANA Cloud includes new RPA and embedded analytics capabilities. One analyst was blunt about his ...

• ### Experts debate whether SAP acquisition of Qualtrics can deliver CX

Ten months after SAP paid \$8 billion for the SaaS experience management platform, experts still differ on what Qualtrics adds to ...

• ### S/4HANA migration concerns lead SAP 2019 stories so far

Industry observers believe that if SAP is to remain competitive, S/4HANA migrations need to pick up, and new leadership needs 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

• ### Can a left shift in Java cause DevOps developer burnout?

DevOps burnout is more common than you think. Pay attention to the details in your Java shift left to make sure your dev and ...

• ### Microsoft gains instant Java credibility with jClarity buy

Microsoft has acquired jClarity to help optimize its Azure cloud platform to run Java workloads, a coveted target for the now ...

• ### How to install the JDK on Windows and set up JAVA_HOME

You have options when it comes to JDK installations on Windows and Linux. Here are some helpful tips to ensure a proper install ...

## SearchDataCenter

• ### IBM Power chip instruction set now open source

IBM opened up its Power server Instruction Set Architecture allowing the open source community to develop more innovative ...

• ### Big Switch updates its Cloud-First Networking portfolio

Big Switch Networks' new products and features aim to help solve issues such as lack of operational consistency, visibility and ...

• ### How to get out of a bad colocation contract

Renegotiation, legal action and cancellation are all options if your colocation service agreement isn't up to par. But each ...

## SearchContentManagement

• ### Box Shield adds tighter controls for content sharing

New Box security features enable file- and folder-level access control, while admins and security staff get machine-learning ...

• ### Evergage launches Data Warehouse, a BI analytics product

Data Warehouse, Evergage's new BI analytics product, is designed to collect and analyze customer data in an effort to provide ...

• ### Upgrades to Nintex Forms simplifies electronic form creation

The new form designer by Nintex brings user-friendly capabilities to Nintex Forms for both electronic form creation and data ...

## SearchHRSoftware

• ### CEO commitment to upskilling employees may boost HR tech

Top CEOs are promising to train their employees and make sure they are ready for an automating world. Whether the promise is real...

• ### Employee engagement technology not a panacea for HR woes

Employee engagement comes in many shapes and forms, leaving employers to scratch their heads at the best way to motivate their ...

• ### Hiring vendor says gender-based AI bias is pervasive

Gender bias in AI algorithms for recruiting and hiring is a big problem, according to the head of Job.com. With a new hire, the ...

Close