Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

รวมค่าจากคอลัมน์ที่มีค่าซ้ำในอีกคอลัมน์หนึ่งใน MySQL

ใช้ SUM() กับ GROUP BY เพื่อรวมค่าตามกลุ่มที่ซ้ำกัน

สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable ( Name varchar(20), Value int ); 
Query OK, 0 rows affected (2.08 sec)
mysql> insert into DemoTable values('Chris',50); 
Query OK, 1 row affected (0.15 sec) 
mysql> insert into DemoTable values('David',90); 
Query OK, 1 row affected (0.19 sec) 
mysql> insert into DemoTable values('Chris',60); 
Query OK, 1 row affected (0.11 sec) 
mysql> insert into DemoTable values('Bob',100); 
Query OK, 1 row affected (0.15 sec) 
mysql> insert into DemoTable values('David',80); 
Query OK, 1 row affected (0.21 sec)

คิวรี่รวม Value ตาม Name

mysql> select Name, sum(Value) as GrandTotal from DemoTable group by Name;

ผลลัพธ์

+-------+------------+ 
| Name  | GrandTotal | 
+-------+------------+ 
| Chris |        110 | 
| David |        170 | 
| Bob   |        100 | 
+-------+------------+ 
3 rows in set (0.03 sec)

Chris: 50+60=110 | David: 90+80=170 | Bob: 100 | GROUP BY รวมแถวที่ Name เหมือนกัน แล้ว SUM รวมค่า Value