ใช้ GROUP BY ... HAVING กรองกลุ่มที่มีผลรวมเกินเกณฑ์
สร้างตารางและเพิ่มข้อมูล
mysql> create table DemoTable782 ( Name varchar(100), Score int );
Query OK, 0 rows affected (1.18 sec)
mysql> insert into DemoTable782 values('John',156); Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable782 values('Carol',250); Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable782 values('Bob',140); Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('John',126); Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable782 values('John',140); Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Bob',280); Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Bob',250); Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable782 values('Carol',189); Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Carol',299); Query OK, 1 row affected (0.21 sec)
คิวรี GROUP BY พร้อม HAVING
mysql> select Name, SUM(Score) AS Total from DemoTable782 group by Name HAVING Total > 500;
+-------+-------+ | Name | Total | +-------+-------+ | Carol | 738 | | Bob | 670 | +-------+-------+ 2 rows in set (0.00 sec)
คำอธิบาย: John รวม 422 (ไม่ผ่านเกณฑ์ 500), Carol 738, Bob 670