25

I have a table full of items and prices for said items. I would like to grab the SUM of the 3 highest priced items.

I thought perhaps SELECT SUM(items.price) FROM items ORDER BY items.price LIMIT 3 but that does not seem to do the trick. Is this possible? Thanks!

PotatoFro
  • 6,378
  • 4
  • 20
  • 22

5 Answers5

45
select sum(price) from (select items.price from items order by items.price desc limit 3) as subt;
KernelM
  • 8,776
  • 2
  • 23
  • 16
16

LIMIT affects the number of rows returned by the query and SUM only returns one. Based on this thread you might want to try:

SELECT sum(price) 
FROM (SELECT price
      FROM items
      ORDER BY price DESC
      LIMIT 3
) AS subquery;
ScottJShea
  • 7,041
  • 11
  • 44
  • 67
2

Just use a sub-select:

select sum(prices) from (SELECT SUM(items.price) FROM items ORDER BY items.price LIMIT 3) as prices
Dave Halter
  • 15,556
  • 13
  • 76
  • 103
1

Use a subquery or something like that. Just an idea, as I have not tested the actual query.

SELECT SUM(items.price) from (select price FROM items ORDER BY items.price LIMIT 3)
Wiseguy
  • 20,522
  • 8
  • 65
  • 81
johnshen64
  • 3,734
  • 1
  • 21
  • 17
  • 1
    Right answer except that it seems when I write `SUM(items.price)` the query fails, but leaving out the table ie. `SUM(price)` the query works – PotatoFro Mar 26 '12 at 19:04
-1

I haven't tested this and I just wrote it on my memory. You could try something like:

SELECT * AS total FROM items ORDER BY price DESC
SELECT SUM(price) FROM total LIMIT 3;

Edit: I was slow

Mare
  • 943
  • 3
  • 11
  • 18