复数派生表的SUM

时间:2016-04-01 01:33:29

标签: mysql sql

如何获得此复杂查询的总和?

寻找money_volume_sum的总和。 (我可以是一个单独的查询,因此我可以将其用作变量来计算百分比。)

另外:有没有办法把它放在同一个查询中?

基于stackoverflow上的这个原始问题: SQL SELECT query with custom column, then summed and grouped by column

干杯!

    SELECT SUM(money_volume) AS money_volume_sum,
    exchange        
    FROM (
        SELECT k.exchange, y.close * y.volume AS money_volume  
        FROM symbols k
        JOIN stocks y ON k.id = y.id  
        WHERE y.t = '20160323'  
        ORDER BY money_volume DESC  
    ) t
    GROUP BY exchange  
    ORDER BY money_volume_sum DESC

1 个答案:

答案 0 :(得分:0)

如果你想在外部查询中使用百分比,你可以在MySQL中使用一个使用变量的技巧:

SELECT exchange, SUM(money_volume) AS money_volume_sum, @s as total_sum
FROM (SELECT k.exchange, y.close * y.volume AS money_volume,
             (@s := @s + y.close * y.volume) as cumesum
      FROM symbols k JOIN
           stocks
           y ON k.id = y.id CROSS JOIN
           (SELECT @s := 0) params
      WHERE y.t = '20160323'  
     ) t
GROUP BY exchange  
ORDER BY money_volume_sum DESC;