在MySQL中创建累积和列
为表添加累积和列(cumulative_sum),需要使用运行总计更新现有列。以下是两种在MySQL中实现此目的的方法:
使用相关子查询:
<code class="language-sql">SELECT t.id, t.count, ( SELECT SUM(x.count) FROM table AS x WHERE x.id <= t.id ) AS cumulative_sum FROM table AS t ORDER BY t.id;</code>
此查询使用嵌套查询根据ID小于或等于当前行ID的行计算每行的累积和。
使用MySQL变量:
<code class="language-sql">SELECT t.id, t.count, (@running_total := @running_total + t.count) AS cumulative_sum FROM table AS t JOIN (SELECT @running_total := 0) AS r ORDER BY t.id;</code>
此方法利用MySQL变量在迭代行时跟踪运行总计。@running_total变量初始化为0,然后为每一行递增计数。
注意:
以上是如何在MySQL中高效创建累积和列?的详细内容。更多信息请关注PHP中文网其他相关文章!