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?

This was last published in June 2005

## Content

Find more PRO+ content and other member only offers, here.

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

• ### Hyperledger Fabric offers path to enterprise blockchain future

Blockchain arose from bitcoin, but it's looking to find a place in the enterprise. Frameworks like Hyperledger Fabric could ...

• ### MongoDB 4.0 takes ACID transactions to multi-document level

MongoDB is taking a deeper step into SQL-style processing waters with a 4.0 update that brings increased support for ...

• ### Data lake concept needs firm hand to pay big data dividends

Data lakes pose technology deployment and data management challenges that can leave analytics users high and dry if the ...

• ### AI functionality limited today but could be a game-changer

Limited AI capabilities could soon give way to technology that is truly transformative for enterprises, surpassing the overhyped ...

## SearchSAP

• ### ControlPanelGRC app eases Steelcase's compliance pain

When Steelcase's SAP environment grew in size and complexity, it turned to Symmetry ControlPanelGRC to save time, have more ...

• ### Translytical data platforms emerge with SAP HANA as a leader

SAP HANA is a leading translytical platform, according to Forrester, and consulting firm Convergent IS says the combination of ...

• ### SAP HANA and Esri combine for geospatial database platform

SAP and Esri are combining SAP HANA's in-memory database capabilities with Esri geospatial applications, and utilities are taking...

## SearchSQLServer

SQL Operations Studio simplifies routine administration of SQL Server and Azure SQL databases, making database development and ...

• ### Meltdown and Spectre fixes eyed for SQL Server performance issues

Microsoft has responded to the Spectre and Meltdown chip vulnerabilities with patches and other fixes. But IT teams need to sort ...

• ### Five SQL Server maintenance steps you should take -- ASAP

Putting off SQL Server administration tasks can lead to database problems. Enact these often-neglected maintenance items to help ...

## TheServerSide.com

• ### Pluralsight IQ, Stack Overflow boost developer street cred

Tying the Pluralsight IQ skills test to the Stack Overflow Developer Story helps developers measure their technical skills and ...

• ### Why this quantum computing breakthrough is a security risk

Quantum computing will void pretty much all security encryption techniques and open the door to hackers. Here's how to protect ...

• ### Database automation drives DevOps into the persistence layer

A new breed of software tools is driving DevOps processes deep into the persistence layer, as database automation and continuous ...

## SearchDataCenter

• ### Evaluate read-intensive and write-intensive SSD use cases

Consider write wear, performance and other factors when choosing between read-intensive, write-intensive and mixed-use ...

• ### Some hyper-converged infrastructure use cases pose pitfalls

Hyper-converged infrastructure adoption is skyrocketing, but that doesn't mean that the technology is the best choice for every ...

• ### Dell hyper-converged reorg streamlines products, ups CI odds

Market pressures and manufacturing synergies drove Dell to integrate its HCI and CI products with its core business units, but ...

## SearchContentManagement

• ### Content management in the cloud a main theme in 2018

The future of content management resides in the cloud and with AI, as several 2018 conferences will assure you.

• ### Six things to know about today's SharePoint implementations

As companies migrate their on-premises Microsoft SharePoint sites to the cloud, here are some things they should know about the ...

• ### Upgrades for the SharePoint Online portal

As more organizations migrate SharePoint sites to the cloud, Microsoft has increased at-a-glance dashboard data and analytics to ...

## SearchHRSoftware

• ### Don't overlook the many benefits of Microsoft Excel for HR

The maligned spreadsheet tool is no substitute for enterprise apps like HRMS and people analytics, but it will do in a pinch and ...

• ### HR is failing to use people analytics tools, new report says

Human resource departments fail to use people analytics tools effectively, a new global study concludes. The findings were called...

• ### Does your company need new human resource management tools?

Finding the best human resource management tools starts with identifying your company's present and future needs, before ...

Close