dpa31905 2012-07-13 06:47
浏览 27
已采纳

MySQL统计查询优化

I'm trying to optimize my queries a bit but can't quite get it right.

I'm looking to get some statistics from a table

I have a query for the top contributors

SELECT `name`, `amount` FROM `customers` ORDER by `amount` DESC LIMIT 10

but I also want to get the SUM and AVG of amount in all records, not just the top 10. I'm not sure how to do this without having a new query for each.

  • 写回答

5条回答 默认 最新

  • douzhe1264 2012-07-13 06:51
    关注

    If you want the top 10 users along with the SUM and AVG of ALL rows in the table, you can make a cartesian product of the SUM and AVG like so:

    SELECT 
        a.name, a.amount, b.amtsum, b.amtavg
    FROM customers a
    CROSS JOIN (SELECT SUM(amount) AS amtsum, AVG(amount) AS amtavg FROM customers) b
    ORDER BY amount DESC
    LIMIT 10
    

    Keep in mind that the values for SUM and AVG will be repeating on all 10 rows returned — they will be the same.

    If you want the sum and averages of amount for each user, you can do:

    SELECT a.name, a.amount, b.amtsum, b.amtavg
    FROM customers a
    INNER JOIN
    (
        SELECT name, SUM(amount) AS amtsum, AVG(amount) AS amtavg
        FROM customers
        GROUP BY name
    ) b ON a.name = b.name
    ORDER BY a.amount DESC
    LIMIT 10
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探