บทความนี้สาธิตการใช้ GROUP BY ร่วมกับ COUNT() เพื่อดึงค่าที่ไม่ซ้ำกัน (Distinct Values) และนับจำนวนครั้งที่ปรากฏของแต่ละค่า
สร้างตารางและข้อมูลราคาสินค้า (มีค่าซ้ำ)
mysql> CREATE TABLE DemoTable754 (ProductPrice INT);
Query OK, 0 rows affected (0.48 sec)
mysql> INSERT INTO DemoTable754 VALUES(200), (500), (200), (500), (800), (900), (200), (200), (900);
คิวรี GROUP BY นับจำนวนแต่ละราคา
mysql> SELECT ProductPrice, COUNT(ProductPrice)
FROM DemoTable754
GROUP BY ProductPrice;
ผลลัพธ์
+--------------+---------------------+
| ProductPrice | count(ProductPrice) |
+--------------+---------------------+
| 200 | 4 |
| 500 | 2 |
| 800 | 1 |
| 900 | 2 |
+--------------+---------------------+
คำอธิบาย:
GROUP BY ProductPrice- จัดกลุ่มแถวที่มี ProductPrice เหมือนกันCOUNT(ProductPrice)- นับจำนวนแถวในแต่ละกลุ่ม (ไม่นับ NULL)- เทียบเท่า
SELECT DISTINCT ProductPrice, COUNT(*) ... GROUP BY ProductPrice - เรียงลำดับอัตโนมัติตาม GROUP BY (ค่า 200, 500, 800, 900)
ความแตกต่าง DISTINCT vs GROUP BY:
SELECT DISTINCT ProductPrice- แค่ค่าที่ไม่ซ้ำGROUP BY ProductPrice- ค่าที่ไม่ซ้ำ + Aggregate Functions (COUNT, SUM, AVG, etc.)