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.

This was last published in November 2012

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

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

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

• ### Avoiding SAP indirect access woes requires good faith

Some customers are concerned that SAP will hit them for indirect access licensing fees, but they can avoid trouble if they act in...

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

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

• ### Limeade releases new employee engagement software

HR tech news roundup: Employee engagement software vendor Limeade expands platform and releases inclusion module for large ...

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

Close