Matt Mitchell
Matt Mitchell

Reputation: 41823

Simple SQL select sum and values of same column

I have a co-worker who is working on a table with an 'amount' column. They would like to get the top 5 amounts and the sum of the amounts in the same query.

I know you could do this:

SELECT TOP 5 amount FROM table 
UNION SELECT SUM(amount) FROM table
ORDER BY amount DESC

But this produces results like this:

1000  (sum)
 100
  70
  50
  30
  20

When what they really need is this:

100 | 1000
 70 | 1000
 50 | 1000
 30 | 1000
 20 | 1000

My intuitive attempts to achieve this tend to run into grouping problems, which isn't such an issue when you are selecting a different column, but is when you want to use an aggregate function based on the column you are selecting.

Upvotes: 0

Views: 12409

Answers (4)

Quassnoi
Quassnoi

Reputation: 425261

Another approach using analytic functions (SQL Server 2005+):

SELECT  TOP 5 amount, SUM(amount) OVER()
FROM    table
ORDER BY
        amount DESC

Upvotes: 1

Thorsten
Thorsten

Reputation: 13181

Not really pretty, but this shouls do it:

SELECT TOP 5 amount,  SAmount
FROM table Join 
  (SELECT SUM(amount) As SAmount FROM table)
ORDER BY amount DESC

As said by others, I'd probably use two queries.

Upvotes: 1

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340171

This might work

SELECT TOP 5 amount, (SELECT SUM(amount) FROM table) 
FROM table 
ORDER BY amount DESC

Upvotes: 2

Bob
Bob

Reputation: 1343

You can use a CROSS JOIN for this:

SELECT TOP 5 a.amount, b.sum
FROM table a
CROSS JOIN (SELECT SUM(amount) sum FROM table) b
ORDER BY amount DESC

Upvotes: 6

Related Questions