Bài 5
Tổng hợp dữ liệu
SUM, AVG, COUNT, GROUP BY
Mục tiêu học tập
- Sử dụng hàm tổng hợp (aggregate functions)
- COUNT, SUM, AVG, MIN, MAX
- GROUP BY để nhóm dữ liệu
- HAVING để lọc sau khi nhóm
Lesson 5: Tổng Hợp Dữ Liệu
Aggregate Functions
COUNT - Đếm số dòng
-- Đếm tổng số sản phẩm
SELECT COUNT(*) as total_products FROM products;
-- Đếm số category khác nhau
SELECT COUNT(DISTINCT category_id) as total_categories FROM products;SUM - Tổng
-- Tổng doanh thu
SELECT SUM(total_amount) as total_revenue FROM sales;AVG - Trung bình
-- Doanh thu trung bình mỗi giao dịch
SELECT AVG(total_amount) as avg_transaction FROM sales;GROUP BY - Nhóm dữ liệu
-- Doanh thu theo từng cửa hàng
SELECT st.store_name, SUM(s.total_amount) as revenue
FROM sales s
JOIN stores st ON s.store_id = st.store_id
GROUP BY st.store_name
ORDER BY revenue DESC;HAVING - Lọc sau GROUP BY
-- Cửa hàng có doanh thu > 50 triệu
SELECT st.store_name, SUM(s.total_amount) as revenue
FROM sales s
JOIN stores st ON s.store_id = st.store_id
GROUP BY st.store_name
HAVING SUM(s.total_amount) > 50000000;SQL Editor
Loading...
Bài tập thực hành
Bài tập 1: Đếm số khách hàng
Gợi ý
COUNT(*) FROM customers
Xem đáp án
SELECT COUNT(*) as total_customers
FROM customers;Bài tập 2: Tính tổng doanh thu theo từng category
Gợi ý
JOIN sales, products, categories và GROUP BY category_name
Xem đáp án
SELECT c.category_name, SUM(s.total_amount) as revenue
FROM sales s
JOIN products p ON s.product_id = p.product_id
JOIN categories c ON p.category_id = c.category_id
GROUP BY c.category_name
ORDER BY revenue DESC;Bài tập 3: Tìm top 5 sản phẩm được bán nhiều nhất (theo quantity)
Gợi ý
SUM(quantity) và GROUP BY product_name, ORDER BY
Xem đáp án
SELECT p.product_name, SUM(s.quantity) as total_sold
FROM sales s
JOIN products p ON s.product_id = p.product_id
GROUP BY p.product_name
ORDER BY total_sold DESC
LIMIT 5;Đang tải schema...