MySQL MySQL选择带有限制的结果总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9877872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL select SUM of results with a LIMIT
提问by PotatoFro
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.
我有一张桌子,里面装满了物品和上述物品的价格。我想获取 3 个最高价商品的总和。
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!
我想也许SELECT SUM(items.price) FROM items ORDER BY items.price LIMIT 3
但那似乎并没有做到这一点。这可能吗?谢谢!
回答by KernelM
select sum(price) from (select items.price from items order by items.price desc limit 3) as subt;
回答by ScottJShea
LIMIT
affects the number of rows returned by the query and SUM only returns one. Based on this threadyou might want to try:
LIMIT
影响查询返回的行数,SUM 只返回一。基于此线程,您可能想尝试:
SELECT sum(price)
FROM (SELECT price
FROM items
ORDER BY price DESC
LIMIT 3
) AS subquery;
回答by johnshen64
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)
回答by Dave Halter
Just use a sub-select:
只需使用子选择:
select sum(prices) from (SELECT SUM(items.price) FROM items ORDER BY items.price LIMIT 3) as prices
回答by Mare
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
编辑:我很慢