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

วิธีนับจำนวนแถวที่มีค่าซ้ำ/ซ้ำสามครั้งในคอลัมน์ของตาราง MySQL


สมมติมีตาราง stock_item ที่คอลัมน์ quantity มีค่าซ้ำ เช่น Notebooks และ Pencil มี quantity = 40 (ซ้ำ 2 ครั้ง) และ Shirts, Shoes, Trousers มี quantity = 29 (ซ้ำ 3 ครั้ง)

mysql> Select * from stock_item;
+------------+----------+
| item_name  | quantity |
+------------+----------+
| Calculator |       89 |
| Notebooks  |       40 |
| Pencil     |       40 |
| Pens       |       32 |
| Shirts     |       29 |
| Shoes      |       29 |
| Trousers   |       29 |
+------------+----------+
7 rows in set (0.00 sec)

ใช้คำสั่งด้านล่างเพื่อหาจำนวนค่าที่ซ้ำ/ซ้ำสามครั้ง:

mysql> Select COUNT(quantity) AS duplicate_triplicate
    -> from stock_item
    -> group by quantity having duplicate_triplicate > 1;
+----------------------+
| duplicate_triplicate |
+----------------------+
|                    3 |
|                    2 |
+----------------------+
2 rows in set (0.00 sec)

ผลลัพธ์: แสดงว่าคอลัมน์ quantity มีค่าหนึ่งที่ซ้ำ 3 ครั้ง (triplicate) และอีกค่าหนึ่งซ้ำ 2 ครั้ง (duplicate)