05 Aggregate Function และ GROUP BY
Aggregate Function และ GROUP BY
SQL ไม่ได้ใช้แค่ดึงข้อมูลรายแถว แต่ยังใช้สรุปข้อมูลเพื่อทำรายงานได้
Aggregate Function
SELECT COUNT(*) AS order_count
FROM orders;
Function ที่ใช้บ่อย:
COUNT()นับจำนวนSUM()รวมผลรวมAVG()ค่าเฉลี่ยMIN()ค่าน้อยสุดMAX()ค่ามากสุด
สรุปยอดขายรวม
SELECT
COUNT(*) AS order_count,
SUM(amount) AS total_amount,
AVG(amount) AS average_amount,
MIN(amount) AS min_amount,
MAX(amount) AS max_amount
FROM orders;
GROUP BY
ใช้สรุปข้อมูลแยกกลุ่ม
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id;
GROUP BY หลาย column
SELECT
order_date,
status,
COUNT(*) AS order_count
FROM orders
GROUP BY order_date, status;
HAVING
WHERE กรองก่อน group ส่วน HAVING กรองหลัง group
SELECT
customer_id,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(amount) >= 5000;
ลำดับการคิด SQL แบบสรุปข้อมูล
SELECT
customer_id,
SUM(amount) AS total_amount
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(amount) >= 5000
ORDER BY total_amount DESC;
แบบฝึกหัด
จาก table orders
- นับจำนวน order ทั้งหมด
- หายอดขายรวม
- สรุปยอดขายรวมแยกตาม
customer_id - หาลูกค้าที่มียอดรวมมากกว่า 10000
- เรียงลูกค้าตามยอดรวมจากมากไปน้อย