-- ========================================================================= -- BÀI 08: THỐNG KÊ TỔNG SỐ LƯỢNG BÁN RA VÀ DOANH THU CỦA TỪNG LOẠI SẢN PHẨM -- Kỹ thuật sử dụng: LEFT JOIN, COALESCE, SUM(oi.quantity), SUM(oi.quantity * oi.price), GROUP BY -- ========================================================================= USE `labdb`; -- Cấu trúc bảng liên quan (Schema): CREATE TABLE IF NOT EXISTS `categories` ( `id` INT AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(100) NOT NULL, `description` VARCHAR(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `products` ( `id` INT AUTO_INCREMENT PRIMARY KEY, `category_id` INT NOT NULL, `name` VARCHAR(150) NOT NULL, `price` DECIMAL(15, 2) NOT NULL DEFAULT 0.00 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `order_items` ( `id` INT AUTO_INCREMENT PRIMARY KEY, `order_id` INT NOT NULL, `product_id` INT NOT NULL, `quantity` INT NOT NULL DEFAULT 1, `price` DECIMAL(15, 2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Câu truy vấn chính của Bài 08: SELECT c.id AS category_id, c.name AS category_name, COALESCE(SUM(oi.quantity), 0) AS total_quantity_sold, COALESCE(SUM(oi.quantity * oi.price), 0) AS total_revenue FROM categories c LEFT JOIN products p ON c.id = p.category_id LEFT JOIN order_items oi ON p.id = oi.product_id GROUP BY c.id, c.name ORDER BY total_revenue DESC, total_quantity_sold DESC;