Bài 6
Sắp xếp dữ liệu
ORDER BY để sắp xếp kết quả
Mục tiêu học tập
- Sử dụng ORDER BY để sắp xếp
- ASC (tăng dần) vs DESC (giảm dần)
- Sắp xếp theo nhiều cột
Lesson 6: Sắp Xếp Dữ Liệu
ORDER BY cơ bản
ASC - Tăng dần (mặc định)
-- Sản phẩm từ rẻ đến đắt
SELECT product_name, unit_price
FROM products
ORDER BY unit_price ASC;DESC - Giảm dần
-- Sản phẩm từ đắt đến rẻ
SELECT product_name, unit_price
FROM products
ORDER BY unit_price DESC
LIMIT 10;Sắp xếp theo nhiều cột
-- Sắp xếp theo category trước, sau đó theo price
SELECT c.category_name, p.product_name, p.unit_price
FROM products p
JOIN categories c ON p.category_id = c.category_id
ORDER BY c.category_name ASC, p.unit_price DESC;Ví dụ thực tế
-- Top 10 giao dịch lớn nhất
SELECT sale_date, total_amount, payment_method
FROM sales
ORDER BY total_amount DESC
LIMIT 10;
-- Doanh thu theo cửa hàng (cao xuống thấp)
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;SQL Editor
Loading...
Bài tập thực hành
Bài tập 1: Sắp xếp khách hàng theo tên (A-Z)
Gợi ý
ORDER BY customer_name ASC
Xem đáp án
SELECT customer_name, city, phone
FROM customers
ORDER BY customer_name ASC;Bài tập 2: Top 5 sản phẩm đắt nhất
Gợi ý
ORDER BY unit_price DESC LIMIT 5
Xem đáp án
SELECT product_name, unit_price, brand
FROM products
ORDER BY unit_price DESC
LIMIT 5;Bài tập 3: Cửa hàng có doanh thu thấp nhất (hiện 3 cửa hàng)
Gợi ý
GROUP BY, SUM, ORDER BY ASC
Xem đáp án
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 ASC
LIMIT 3;Đang tải schema...