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

# Using SQL SELECT and SQL UNION ALL statements to sort numbers

## Expert Dan Clamage explains how to use SQL SELECT and SQL UNION ALL statements to sort and visualize a set of sales figures.

I'd like to get number for composing a graph of sales. Considering we have a lot of items in our store, I'd like to visualize just the nth biggest values and aggregate all the others. For example: If I have 100 items, I want to pull values greater than \$1,000. All others would be aggregated so that I can get something like this:

1. Product A: \$10,000
2. Product B: \$12,000
3. Product C: \$8,000
4. Other: \$18,000 (the sum of smaller values)

How can I do that?

This actually sounds like two SQL SELECT queries to me. In the first place, you'd like to aggregate by product whose aggregate sales values exceed \$1,000. On the other hand, you'd like to aggregate as Other all of those products whose aggregate values are \$1,000 or less. So, I would write and test each query separately, then combine them with UNION ALL.

For example:

-- Top N Sales > 1000
SELECT ps.product_name, SUM(ps.sales) sales
FROM product_sales ps
GROUP BY ps.product_name
HAVING SUM(ps.sales) > 1000;

-- everything else
SELECT ps.product_name, SUM(ps.sales) sales
FROM product_sales ps
GROUP BY ps.product_name
HAVING SUM(ps.sales) <= 1000;

You probably have certain filter criteria, such as only for the current calendar year or some fiscal year or quarter, perhaps. Since you'd like everything else to be aggregated under Other, you can simply do this with that SQL SELECT query:

-- everything else, aggregated as Other
SELECT 'Other' product_name, SUM(tps.sales) sales
FROM (SELECT ps.product_name, SUM(ps.sales) sales
FROM product_sales ps
GROUP BY ps.product_name
HAVING SUM(ps.sales) <= 1000
) tps
GROUP BY 'Other';

#### More on SQL SELECT statements

Check out how to use a SQL SELECT statement on a nonexistent table

Find out how to debug poor response time when running a SQL SELECT statement

Discover how to translate information requests into SQL SELECT statements

Note that the GROUP BY has to match the scalar (nonaggregated) columns given in the SELECT clause. In this case, we're discarding the actual product names and aggregating them all under a literal string instead.

Now, you can combine the two data sets and sort them by descending sales using SQL UNION ALL:

-- Top N Sales > 1000
SELECT ps.product_name, SUM(ps.sales) sales
FROM product_sales ps
GROUP BY ps.product_name
HAVING SUM(ps.sales) > 1000
UNION ALL

-- everything else, aggregated as "Other"
SELECT 'Other' product_name, SUM(tps.sales) sales
FROM (SELECT ps.product_name, SUM(ps.sales) sales
FROM product_sales ps
GROUP BY ps.product_name
HAVING SUM(ps.sales) <= 1000
) tps
GROUP BY 'Other'
ORDER BY sales DESC, product_name;

If you want Other to always wind up at the bottom of the sorted set (in the case where otherwise all of the other small aggregates would wind up being bigger than the larger individual aggregates), then the ORDER BY can use an expression like the following:

ORDER BY DECODE(product_name, 'Other', -sales, sales) DESC, product_name;

This would always make just the one Other row sort to the bottom of the list, assuming aggregate sales are never negative. I included product_name as the sort tiebreaker in the probably infrequent case where two products' aggregate sales are identical. It's probably no big deal, but it's good to write queries in such a way as to guarantee consistent behavior.

#### Join the conversation

Send me notifications when other members comment.
SELECT 'Other' product_name, SUM(tps.sales) sales
FROM (SELECT ps.product_name, SUM(ps.sales) sales
FROM product_sales ps
GROUP BY ps.product_name
HAVING SUM(ps.sales) <= 1000
) tps
GROUP BY 'Other';

You don't need group by at all, since you are adding all records selected ...

SELECT 'Other' product_name, SUM(tps.sales) sales
FROM (SELECT ps.product_name, SUM(ps.sales) sales
FROM product_sales ps
GROUP BY ps.product_name
HAVING SUM(ps.sales) <= 1000
) tps;

Cancel
Without UNION:
SELECT CASE WHEN rn<4 THEN product_name ELSE 'other' END product_name, Sum(sales) sales
FROM (
SELECT Row_Number() over(ORDER BY sales desc) rn, product_name, sales FROM product_sales
)
GROUP BY CASE WHEN rn<4 THEN rn ELSE 4 END,CASE WHEN rn<4 THEN product_name ELSE 'other' END
ORDER BY 2,1
;
http://www.sql-tutorial.ru/en/book_row_number_function.html
Cancel
Why did you fail to post DDL? That is minimal Netiquette. Does your boss treat you like this?

SELECT X.product_name, SUM (X.product_price) AS
FROM (SELECT (CASE WHEN product_price < 1000.00
THEN '{{cheap stuff}}'
ELSE product_name END)
AS product_name,
product_price
FROM Products) AS X (product_name, product_price)
GROUP BY X.product_name;
Cancel
SELECT X2.product_name, SUM(X2.sales_amt_tot) AS sales_amt_tot
FROM (SELECT CASE WHEN X1.sales_amt_tot > 1000.00
THEN X1.product_name ELSE 'Losers' END
X1.sales_amt_tot
FROM (SELECT product_name, SUM(sales_amt)
FROM Product_Sales ps
GROUP BY product_name)
AS X1(product_name, sales_amt_tot)
) AS X2(product_name, sales_amt_tot)
GROUP BY product_name;
Cancel

## SearchDataManagement

• ### PlanetScale extends multi-cloud database as a service

Open source-based PlanetScaleDB adds support for Microsoft Azure, enabling a multi-cloud database as a service platform that ...

• ### Oracle NoSQL database comes to the cloud

Another Oracle database is coming to the cloud with the general availability of Oracle NoSQL Database Cloud Service as the demand...

• ### MariaDB SkySQL enables cloud-native database as a service

MariaDB brings back an old name for its cloud-native database-as-a-service platform. MariaDB CEO Michael Howard details how he's ...

• ### Importance of analytics clear amid COVID-19 crisis

With health organizations and business leaders alike trying to minimize the effects of COVID-19, analytics is playing a critical ...

• ### AI tools in analytics software key in fighting COVID-19

With data skewed by incomplete testing, augmented intelligence and machine learning tools are helping data scientists create ...

• ### Should your company hire a freelance data scientist?

Enterprises need to make the right hiring choices when it comes to supporting their data projects. Here are some reasons your ...

## SearchSAP

• ### SAP S/4HANA deployment options: Legacy ERP vs. cloud

Take this tour of the on-premises S/4HANA and its two cloud siblings and get expert advice on major differences in cost and ...

• ### Floating the possibilities of SAP S/4HANA Cloud migration

When weighing the advantages of abandoning legacy ERP systems for SAP S/4HANA Cloud, factors include implementation and support ...

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

• ### Eclipse launches Theia 1.0 as alternative to VS Code

The Eclipse Foundation's Theia framework for building desktop and cloud IDEs has the potential to be as big as the initial ...

• ### Developing a COVID-19 application? Design it the right way

Application developers with skills and an idea could design an app to combat the virus. Follow these insights to effectively ...

• ### How developers can volunteer during the COVID-19 pandemic

What resources can developers offer to go against COVID-19? Explore some promising developer volunteer and open source project ...

## SearchDataCenter

• ### Build a migration plan for enterprise edge infrastructure

Micro data centers are essential to edge computing use cases. Build an effective migration plan through site selection, ...

• ### Tech giants aim supercomputers, clouds at finding a COVID-19 cure

The new COVID-19 HPC consortium comprised of tech giants, national labs and academia are using supercomputers and clouds to speed...

• ### Top vendor SDDC certification programs for admins

If you decide to grow your knowledge of software-defined data center technologies, VMware, Nuage Networks and Microsoft offer ...

## SearchContentManagement

• ### Creating digital experiences key to driving exceptional CX

The way in which businesses build digital experiences is ever-evolving. It's a race to create easier-to-use customer interfaces ...

• ### Vendors offer free remote work technology for telecommuting

It's more than a marketing ploy: Cloud technology vendors, seeing their own issues enabling remote work, extend paid products to ...

• ### How businesses should deal with enterprise search issues

Enterprise search issues frequently complicate user experience with ECM systems. While users may face many problems, they also ...

## SearchHRSoftware

• ### How to create an employee journey map

This handy guide shows you how to build your own employee journey map, which is more important than ever as the coronavirus ...

• ### Remote team tech Sneek keeps co-workers in view

Sneek, a remote team platform, uses frequently updated photographs of remote workers to connect co-workers together.

• ### Best-case, worst-case pandemic scenarios for India service providers

India's IT and business support services will be tested during that country's pandemic lockdown. Many workers are now operating ...

Close