MySQL select SUM of results with a LIMIT

2019-01-14 21:38发布

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!

标签: mysql sum
5条回答
来,给爷笑一个
2楼-- · 2019-01-14 22:22

Just use a sub-select:

select sum(prices) from (SELECT SUM(items.price) FROM items ORDER BY items.price LIMIT 3) as prices
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-14 22:23

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

查看更多
倾城 Initia
4楼-- · 2019-01-14 22:34
select sum(price) from (select items.price from items order by items.price desc limit 3) as subt;
查看更多
Animai°情兽
5楼-- · 2019-01-14 22:34

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;
查看更多
该账号已被封号
6楼-- · 2019-01-14 22:36

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)
查看更多
登录 后发表回答