Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select SUM of results with a LIMIT

Tags:

mysql

sum

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!

like image 631
PotatoFro Avatar asked Mar 26 '12 18:03

PotatoFro


People also ask

How do I LIMIT the number of results in MySQL?

In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count. The value of both the parameters can be zero or positive integers.

Is there a LIMIT clause in MySQL?

The MySQL LIMIT Clause The LIMIT clause is used to specify the number of records to return. The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.

Can I do a sum of a count in MySQL?

COUNT() is used to count the number of rows for a given condition. COUNT() works on numeric as well as non-numeric values. SUM() is used to calculate the total sum of all values in the specified numeric column.

What is the LIMIT clause with SELECT query?

The LIMIT clause can restrict the result set of the query to some maximum number of rows. If this clause specifies a value smaller than the number of qualifying rows, the query returns only a subset of the rows that satisfy the selection criteria.


2 Answers

select sum(price) from (select items.price from items order by items.price desc limit 3) as subt;
like image 189
KernelM Avatar answered Oct 23 '22 18:10

KernelM


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;
like image 16
ScottJShea Avatar answered Oct 23 '22 19:10

ScottJShea