Erstellen Sie eine Spalte für die kumulative Summe in MySQL
P粉670838735
P粉670838735 2023-08-22 11:26:08
0
2
448
<p>Ich habe eine Tabelle, die so aussieht:</p> <pre class="brush:php;toolbar:false;">ID-Anzahl 1 100 2 50 3 10</pre> <p>Ich möchte eine neue Spalte namens cumulative_sum hinzufügen, sodass die Tabelle so aussieht: </p> <pre class="brush:php;toolbar:false;">id count cumulative_sum 1 100 100 2 50 150 3 10 160</pre> <p>Gibt es eine MySQL-Update-Anweisung, mit der dies leicht erreicht werden kann? Was ist der beste Ansatz? </p>
P粉670838735
P粉670838735

Antworte allen(2)
P粉245276769

使用相关查询:


SELECT t.id,
         t.count,
         (SELECT SUM(x.count)
            FROM TABLE x
           WHERE x.id <= t.id) AS cumulative_sum
    FROM TABLE t
ORDER BY t.id

使用MySQL变量:


SELECT t.id,
         t.count,
         @running_total := @running_total + t.count AS cumulative_sum
    FROM TABLE t
    JOIN (SELECT @running_total := 0) r
ORDER BY t.id

注意:

  • JOIN (SELECT @running_total := 0) r是一个交叉连接,允许在不需要单独的SET命令的情况下声明变量。
  • MySQL要求为任何子查询/派生表/内联视图提供表别名r

注意事项:

  • 仅适用于MySQL,不可移植到其他数据库
  • ORDER BY非常重要,它确保顺序与原始问题匹配,并且对于更复杂的变量使用(例如:伪ROW_NUMBER/RANK功能,MySQL不支持)可能会有更大的影响
P粉006540600

如果性能是一个问题,你可以使用MySQL变量:

set @csum := 0;
update YourTable
set cumulative_sum = (@csum := @csum + count)
order by id;

或者,你可以移除cumulative_sum列,并在每个查询中计算它:

set @csum := 0;
select id, count, (@csum := @csum + count) as cumulative_sum
from YourTable
order by id;

这样以一种连续的方式计算累积和 :)

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!