การคำนวณ Running Total (Cumulative Sum)
ใช้ Session Variable (@var) เพื่อเก็บผลรวมสะสมระหว่างการประมวลผลแต่ละแถว
ตัวอย่าง
mysql> create table DemoTable809(Price int);
Query OK, 0 rows affected (0.53 sec)
mysql> insert into DemoTable809 values(40);
mysql> insert into DemoTable809 values(50);
mysql> insert into DemoTable809 values(60);
คำสั่ง Running Total
mysql> select @currentSum := @currentSum + Price from DemoTable809;
ผลลัพธ์:
+--------------------------------+
| @currentSum := @currentSum+Price |
+--------------------------------+
| 40 |
| 90 |
| 150 |
+--------------------------------+
เวอร์ชันที่สมบูรณ์กว่า (มี INIT)
SELECT
Price,
@running_total := @running_total + Price AS running_total
FROM DemoTable809
CROSS JOIN (SELECT @running_total := 0) AS init
ORDER BY Price;
ผลลัพธ์:
+-------+---------------+
| Price | running_total |
+-------+---------------+
| 20 | 20 |
| 30 | 50 |
| 50 | 100 |
+-------+---------------+
MySQL 8.0+: ใช้ Window Function (แนะนำ)
SELECT
Price,
SUM(Price) OVER (ORDER BY Price) AS running_total
FROM DemoTable809;
Window Function เป็นมาตรฐาน ANSI SQL อ่านง่าย ไม่ต้องใช้ Variable และรองรับ PARTITION BY
สรุป
- MySQL < 8.0: ใช้ Session Variable (
@var) - MySQL 8.0+: ใช้
SUM() OVER (ORDER BY ...)(แนะนำ) - จำเป็นต้องมี
ORDER BYเพื่อกำหนดลำดับการสะสม