Skip to content

Aggregate Functions

Aggregate Functions คืออะไร?

Section titled “Aggregate Functions คืออะไร?”

Aggregate function รับข้อมูลหลายแถวเป็น input แล้วส่งกลับค่าเดียวเป็น output

เหมือนฟังก์ชัน =COUNT(A:A), =SUM(D:D), =AVERAGE(D:D) ที่ท้าย column

ความแตกต่างที่สำคัญมาก:

-- COUNT(*) นับทุกแถว รวม NULL
SELECT COUNT(*) FROM students;
-- ผลลัพธ์: 6 (ทุกแถว)
-- COUNT(column) นับเฉพาะแถวที่ column นั้นไม่เป็น NULL
SELECT 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_price
FROM students
WHERE active = TRUE;

ผลลัพธ์:

total_studentstotal_revenueavg_pricemin_pricemax_price
421700.005425.003200.009500.00

WHERE กรองแถวก่อนที่ aggregate จะทำงาน:

-- จำนวนนักเรียนที่สมัครในปี 2025
SELECT COUNT(*) AS students_2025
FROM students
WHERE enrolled_on >= '2025-01-01'
AND enrolled_on < '2026-01-01';
-- ผลลัพธ์: 4
-- ค่าเรียนเฉลี่ยเฉพาะคนที่จ่ายเกิน 3000
SELECT AVG(price) AS avg_premium
FROM students
WHERE price > 3000;
-- ผลลัพธ์: 5900.00
-- นับจำนวนราคาที่แตกต่างกัน
SELECT COUNT(DISTINCT price) AS unique_prices
FROM students;
-- ผลลัพธ์: 5 (เพราะ 4500 ซ้ำ 2 คน)
-- รวมเฉพาะราคาที่ไม่ซ้ำ
SELECT SUM(DISTINCT price) AS sum_unique_prices
FROM students;
-- ผลลัพธ์: 27100.00 (ไม่นับ 4500 ซ้ำ)