Aggregate Functions
Aggregate Functions คืออะไร?
Section titled “Aggregate Functions คืออะไร?”Aggregate function รับข้อมูลหลายแถวเป็น input แล้วส่งกลับค่าเดียวเป็น output
เหมือนฟังก์ชัน =COUNT(A:A), =SUM(D:D), =AVERAGE(D:D) ที่ท้าย column
// ต้อง loop เองทุกครั้งint count = 0;double sum = 0;for (int i = 0; i < n; i++) { count++; sum += students[i].price;}double avg = sum / count;len(df) # COUNTdf["price"].sum() # SUMdf["price"].mean() # AVGdf["price"].min() # MINdf["price"].max() # MAX-- นับจำนวนนักเรียนทั้งหมดSELECT COUNT(*) AS total_students FROM students;-- ผลลัพธ์: 6
-- รวมค่าเรียนทั้งหมดSELECT SUM(price) AS total_revenue FROM students;-- ผลลัพธ์: 31600.00
-- ค่าเรียนเฉลี่ยSELECT AVG(price) AS avg_price FROM students;-- ผลลัพธ์: 5266.67
-- ค่าเรียนต่ำสุดและสูงสุดSELECT MIN(price) AS cheapest, MAX(price) AS most_expensiveFROM students;-- ผลลัพธ์: 2100.00, 9500.00COUNT(*) vs COUNT(column)
Section titled “COUNT(*) vs COUNT(column)”ความแตกต่างที่สำคัญมาก:
-- COUNT(*) นับทุกแถว รวม NULLSELECT COUNT(*) FROM students;-- ผลลัพธ์: 6 (ทุกแถว)
-- COUNT(column) นับเฉพาะแถวที่ column นั้นไม่เป็น NULLSELECT COUNT(email) FROM students;-- ผลลัพธ์: 5 (STD005 ไม่มี email จึงไม่ถูกนับ)รวมหลาย Aggregate ใน Query เดียว
Section titled “รวมหลาย Aggregate ใน Query เดียว”SELECT COUNT(*) AS total_students, SUM(price) AS total_revenue, AVG(price) AS avg_price, MIN(price) AS min_price, MAX(price) AS max_priceFROM studentsWHERE active = TRUE;ผลลัพธ์:
| total_students | total_revenue | avg_price | min_price | max_price |
|---|---|---|---|---|
| 4 | 21700.00 | 5425.00 | 3200.00 | 9500.00 |
Aggregate กับ WHERE
Section titled “Aggregate กับ WHERE”WHERE กรองแถวก่อนที่ aggregate จะทำงาน:
-- จำนวนนักเรียนที่สมัครในปี 2025SELECT COUNT(*) AS students_2025FROM studentsWHERE enrolled_on >= '2025-01-01' AND enrolled_on < '2026-01-01';-- ผลลัพธ์: 4
-- ค่าเรียนเฉลี่ยเฉพาะคนที่จ่ายเกิน 3000SELECT AVG(price) AS avg_premiumFROM studentsWHERE price > 3000;-- ผลลัพธ์: 5900.00DISTINCT ใน Aggregate
Section titled “DISTINCT ใน Aggregate”-- นับจำนวนราคาที่แตกต่างกันSELECT COUNT(DISTINCT price) AS unique_pricesFROM students;-- ผลลัพธ์: 5 (เพราะ 4500 ซ้ำ 2 คน)
-- รวมเฉพาะราคาที่ไม่ซ้ำSELECT SUM(DISTINCT price) AS sum_unique_pricesFROM students;-- ผลลัพธ์: 27100.00 (ไม่นับ 4500 ซ้ำ)