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

# Querying derived tables

I have two tables, with the following fields:

```table1
tyear  country  value1
1998     US      32
1998     US      21
2000     CN      90
2001     US      12

table2
tyear  country  value2
1998     US      11
1998     US      80
2000     CN      90
2001     US      15```

I simply want to sum value1 and value2, and then get the difference between them in one SQL expression. For example, first I choose the date then the country, then I have many results in value1 and value2, and I want to sum value1 and value2 then get the difference between both in another field like "diff". So if I choose tyear=1998 and country=US, what I want is this:

```query result
tyear  country  value1  value2   diff
1998     US      53      91      -38```

The solution will involve a derived table for each of your two tables. A derived table is just a subquery, and since a subquery, like any query, produces a result set, we simply treat the subquery result set just as we would an ordinary table. This property of SQL is called orthogonality:

ORTHOGONAL
From the Greek for "having straight angles". A language is orthogonal if analogous situations have similar rules. For example, in SQL-89 a subquery was legal in a WHERE clause but not in a SELECT list; now it is legal in both places, so in this respect we can say that "SQL-92 is more orthogonal than SQL-89".
-- SQL Glossary

In this case we want to use two derived tables in the FROM clause, like this:

```select dt1.tyear
, dt1.country
, dt1.sumvalue1 as value1
, dt2.sumvalue2 as value2
, dt1.sumvalue1
-dt2.sumvalue2 as diff
from (
select tyear
, country
, sum(value1) as sumvalue1
from table1
group
by tyear
, country
) as dt1
inner
join (
select tyear
, country
, sum(value2) as sumvalue2
from table2
group
by tyear
, country
) as dt2
on dt1.tyear
= dt2.tyear
and dt1.country
= dt2.country
where dt1.tyear = 1998
and dt1.country = 'US' ```

This is the form of the query which allows for easiest maintenance, since you have to specify the tyear and country in only one spot.

A similar query, that also produces what you want, is:

```select 1998 as tyear
, 'US' as country
, dt1.sumvalue1 as value1
, dt2.sumvalue2 as value2
, dt1.sumvalue1
-dt2.sumvalue2 as diff
from (
select sum(value1) as sumvalue1
from table1
where tyear = 1998
and country = 'US'
) as dt1

cross
join (
select sum(value2) as sumvalue2
from table2
where tyear = 1998
and country = 'US'
) as dt2```

Can you see the difference? In the second query, the subqueries do not use a GROUP BY. Nevertheless, can you see that they will produce the same results? Which query do you think will be more efficient?

Which query would you use if you needed the difference for two separate tyears?

## SearchDataManagement

• ### Pandemic triggered data security movement to DBaaS

Database-as-a-service technology has aided enterprises tasked with keeping data secure with IT professionals working from home ...

• ### Who belongs on a high-performance data governance team?

Putting together a high-quality data governance team can be a challenge. Explore the necessary team members and best practices ...

• ### Soda launches cloud service to improve data observability

Data quality vendor Soda has had a busy 2021, building out new services and raising funding to help organizations identify and ...

• ### 15 data science tools to consider using in 2021

Numerous tools are available for data science applications. Read about 15, including their features, capabilities and uses, to ...

• ### Insightsoftware acquisition of Izenda targets embedded BI

ERP vendor Insightsoftware acquired embedded analytics specialist Izenda on April 15, marking its second purchase of an embedded ...

• ### Data scientist shortage leaves organizations uncertain

Despite their desire to use data science in their decision-making process, some organizations can't find qualified data ...

## SearchSAP

• ### S/4HANA Cloud SaaS ERP: Buying team overview

SAP's multi-tenant SaaS ERP, S/4HANA Cloud, is a viable choice for companies that need ease in their infrastructure management. ...

• ### SAP forms financial services partnership with Dediq

SAP and financial industry investment firm Dediq are forming a new business unit to develop applications that help banks and ...

• ### Unpatched applications threaten SAP security

Cyberattacks are a significant threat to unpatched, unprotected SAP applications, according to a new threat intelligence report ...

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

• ### Incorporate diversity and inclusion in technology design

DEI in technology is about more than creating a diverse workplace. We talked to a few DEI professionals about how teams build ...

• ### Microsoft previews OpenJDK distro to the delight of devs

In a move meant to attract more Java developers to its Azure cloud and further support the Java community, Microsoft launched a ...

• ### Supreme Court ruling on Java APIs eases developer worries

Now that the Supreme Court has ruled for Google over Oracle in their high-stakes copyright battle over Java APIs, developers can ...

## SearchDataCenter

• ### Programmable processor technology for next-gen data centers

The right processing technology can benefit your data center. Learn about advancements in CPU technologies, recent vendor ...

• ### Data processing units accelerate infrastructure performance

DPUs often run on networking packets to move information in the data center, instead of supporting processing workflows. Get an ...

• ### New Intel Ice Lake processors boost performance, security

Intel launches third-generation Xeon Scalable processors that bolster security, accelerate common data center workloads by 46% on...

## SearchContentManagement

• ### OpenText releases Cloud Editions content services updates

OpenText CE 21.2 includes federated document compliance that extends to Microsoft Office 365, along with a revamped content ...

As the pandemic disrupts paper workflows, Adobe courts small business users with simple webforms, digital signatures and payments...

• ### Know when to use a headless CMS and when it's not worth it

Headless CMSes aren't a silver bullet for every circumstance. Evaluate three solid use cases for a headless CMS and three ...

## SearchHRSoftware

• ### Face mask detection a newcomer to employee surveillance

Face mask detection has emerged as another form of employee surveillance technology, and its adoption may be helped indirectly by...

• ### 20 diversity and inclusion tools to power your DEI program

Diversity and inclusion tools shouldn't replace strategy, but these tools can help companies in multiple ways, from tracking ...

• ### DEI tools arrive at critical time for HR

Employers are being held accountable for meeting diversity, equity and inclusion goals, especially executives. HR vendors are ...

Close