คำอธิบาย
บทความนี้แสดงวิธีการรวมค่า (SUM) ของคอลัมน์เฉพาะแถวที่ตรงตามเงื่อนไข โดยใช้ WHERE clause
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
ProductAmount int,
CustomerCountryName varchar(10) );
Query OK, 0 rows affected (0.86 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable(ProductAmount, CustomerCountryName) values(190, 'US'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(ProductAmount, CustomerCountryName) values(200, 'UK'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(ProductAmount, CustomerCountryName) values(1500, 'AUS'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(ProductAmount, CustomerCountryName) values(2010, 'US'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(ProductAmount, CustomerCountryName) values(7890, 'UK'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(ProductAmount, CustomerCountryName) values(500, 'US'); Query OK, 1 row affected (0.21 sec)
แสดงข้อมูลทั้งหมด
mysql> select * from DemoTable;
ผลลัพธ์:
+------------+---------------+---------------------+ | CustomerId | ProductAmount | CustomerCountryName | +------------+---------------+---------------------+ | 1 | 190 | US | | 2 | 200 | UK | | 3 | 1500 | AUS | | 4 | 2010 | US | | 5 | 7890 | UK | | 6 | 500 | US | +------------+---------------+---------------------+ 6 rows in set (0.00 sec)
คิวรี่ SUM เฉพาะประเทศ US
mysql> select SUM(ProductAmount) AS Total_Amount from DemoTable where CustomerCountryName = 'US';
ผลลัพธ์
+--------------+ | Total_Amount | +--------------+ | 2700 | +--------------+ 1 row in set (0.00 sec)
คำอธิบาย
คำนวณ 190 + 2010 + 500 = 2700 (เฉพาะแถวที่ Country = 'US')
ขยายความ: Conditional Aggregation
หากต้องการ SUM หลายเงื่อนไขในคิวรี่เดียว ให้ใช้ CASE WHEN:
select
SUM(CASE WHEN CustomerCountryName = 'US' THEN ProductAmount ELSE 0 END) as US_Total,
SUM(CASE WHEN CustomerCountryName = 'UK' THEN ProductAmount ELSE 0 END) as UK_Total,
SUM(CASE WHEN CustomerCountryName = 'AUS' THEN ProductAmount ELSE 0 END) as AUS_Total
from DemoTable;