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

# Row sums and the "totals" row

My company is using Oracle and I'd like to make a report, as below:

```a          b          sum
1          10         11
2          20         22
total_a    total_b    total_all
```

What's the SQL command to get the "sum"?

The answer is pretty simple, at least as far as getting the sum of a + b on each row --

```select a
, b
, (a + b) as sum
from yourTable```

Obtaining the "totals" row is a bit trickier. In the example, this would be total_a, total_b, and total_all.

You could use Oracle's proprietary SQL extension called PL/SQL (PL = procedural language) to produce the column totals. Sybase and Microsoft SQL/Server have a similar language extension called Transact-SQL. Both PL/SQL and Transact-SQL provide mechanisms whereby a "totals" row is calculated as a by-product of the report.

If you do not have a procedural language available to do the totals row, you may be interested in the following solution which involves generating the totals row through simple SQL --

```   select "detail"
, a
, b
, (a + b) as sum
from yourTable
union all
select "total"
, sum(a)
, sum(b)
, sum(a + b)
from yourTable
order by 1
, 2```

The query consists of two subqueries, and the results of these subqueries are UNIONed. The first subquery obtains all the detail rows, while the second subquery obtains the single totals row. The second subquery is a good example of aggregate functions being used without a GROUP BY clause -- when there is no GROUP BY clause, the entire table forms the group, and the result is one row.

So in the combined result set from the two subqueries, the first column is used to distinguish detail rows from the totals row. This column is used in the ORDER BY clause, and the values that I chose, the strings "detail" for detail rows and "total" for the totals row, were completely arbitrary, except for the single fact that as it happens, alphabetically, "detail" precedes "total" so the totals row comes at the end. (Neat, eh?) I usually use the values 1 and 2 (because for one thing, they're shorter -- don't forget, they're on each row) except in this case the values 1 and 2 would easily be confused with the ordinal numbers 1 and 2 in the ORDER BY clause, which refer to the first and second columns of the result set of the UNION.

Within the block of detail rows, rows are sequenced by values of a, the second column. The total row is in a block of rows by itself, and this block is sequenced too, but since there's only one total, this doesn't really matter.

UNION ALL is specified instead of UNION, because we know there will never be any duplicate rows between the first and second subqueries, since the first column is perforce different. UNION would invoke a sort in order to detect duplicate rows, so we use UNION ALL to make the query more efficient.

• The Best SQL Web Links: tips, tutorials, scripts, and more.
• Have a SQL tip to offer your fellow DBA's and developers? The best tips submitted will receive a cool prize--submit your tip today!
• Ask your technical SQL questions--or help out your peers by answering them--in our live discussion forums.
• Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.

## SearchDataManagement

• ### Informatica takes Customer 360 master data management to cloud

Updated MDM service benefits from integrations with the broader cloud-native Informatica platform that is built on top of a ...

• ### Graph database vs. relational database: Key differences

Relational databases and graph databases both focus on the relationships between data but not in the same ways. Here are some key...

• ### ScyllaDB NoSQL database to improve with Project Circe

ScyllaDB Project Circe sets out to help improve consistency, elasticity and performance for the open source NoSQL database.

• ### Key differences in uses of DataOps vs. DevOps

As with DevOps, DataOps hinges on cooperation between teams and breaking down silos within an organization with the focus of ...

• ### Data storytelling a key part of Yellowfin analytics platform

Data storytelling remains a focal point for Yellowfin. Stories, the vendor's narrative generation tool, features heavily in both ...

• ### Assent Compliance automates text analytics with AWS

With more than 20,000 documents to review each month, Assent Compliance, a supply chain data management vendor, turned to AWS to ...

## SearchSAP

• ### SAP Commerce Cloud dresses up digital storefronts

SAP Commerce Cloud is designed to help companies launch digital commerce sites, which may be useful for large enterprises and ...

• ### SAP Business Network, S/4HANA critical for SAP in 2021

SAP's 2021 will be a mix of familiar challenges such as moving customers off legacy systems to S/4HANA and new opportunities such...

• ### SAP in 2020: COVID-19, Klein takes command and Qualtrics IPO

From leadership changes to the massive disruptions caused by the COVID-19 pandemic, it was a year like no other for SAP. Here are...

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

• ### What's in a name? What developers can expect in Jakarta EE 9

What Oracle called the Java EE API is now called Jakarta EE API under the Eclipse Foundation. Here's what developers can expect ...

• ### Test your knowledge of variable naming conventions

What's the difference between snake case and camel case? Or kebab case and pascal case? Try this 10-question variable naming quiz...

• ### Why GitHub renamed its master branch to main

The GitHub master branch is no more. Developers used to think it was untouchable, but that's not the case. Here's why GitHub made...

## SearchDataCenter

• ### Get a template to estimate server power consumption per rack

Admins can struggle with power consumption estimation as infrastructure gets more complex. The kW-per-rack metric can help ...

• ### When the chips are down, Intel turns to VMware's Pat Gelsinger

Newly appointed Intel CEO Pat Gelsinger brings technical chops to the top of the giant chipmaker, but it may take a while to ...

• ### Intel CEO Bob Swan to be replaced by VMware's Pat Gelsinger

Facing delays of critical products along with superior offerings by AMD and Nvidia the past couple of years, Intel CEO is ...

## SearchContentManagement

• ### 5 steps to a successful ECM implementation

Implementing an ECM system is a major undertaking. Check out these steps to get on the right track before you jump into the ...

• ### How to develop an ECM strategy and roadmap

Without an ECM roadmap, an organization's strategy can get muddled and disorganized. Understand the steps and strategies to ...

• ### How to achieve Teams integration with SharePoint sites

Depending on the complexity of a business's SharePoint sites, a Teams integration can benefit organizations by being ...

## SearchHRSoftware

• ### Overview of SAP SuccessFactors HXM Suite

SAP SuccessFactors HXM is the next iteration of SuccessFactors HCM and is meant to help HR departments manage the entire employee...

• ### Workday adds vaccine management for 45M to its platform

COVID-19 vaccine management is getting the attention of HR vendors. Workday announced its vaccine tool, which integrates with the...

• ### Democrats push for AI bias testing

Lawmakers in states and Congress are showing increasing interest in guarding against AI bias. Legislation in California and New ...

Close