Để tìm giá trị lớn nhất (MAX) của một cột số ứng với từng giá trị trùng lặp của cột khác, bạn dùng MAX() kết hợp GROUP BY.
Ví dụ minh họa
Tạo bảng sản phẩm:
mysql> create table DemoTable(
ProductName varchar(100),
ProductPrice int
);
Chèn dữ liệu (Product-1, Product-2, Product-3 lặp lại nhiều lần):
mysql> insert into DemoTable values('Product-1',56);
mysql> insert into DemoTable values('Product-2',78);
mysql> insert into DemoTable values('Product-1',88);
mysql> insert into DemoTable values('Product-2',86);
mysql> insert into DemoTable values('Product-1',45);
mysql> insert into DemoTable values('Product-3',90);
mysql> insert into DemoTable values('Product-2',102);
mysql> insert into DemoTable values('Product-3',59);
Hiển thị dữ liệu:
mysql> select * from DemoTable;
Kết quả:
+-------------+--------------+ | ProductName | ProductPrice | +-------------+--------------+ | Product-1 | 56 | | Product-2 | 78 | | Product-1 | 88 | | Product-2 | 86 | | Product-1 | 45 | | Product-3 | 90 | | Product-2 | 102 | | Product-3 | 59 | +-------------+--------------+
Truy vấn MAX(ProductPrice) theo ProductName
mysql> select ProductName, MAX(ProductPrice) from DemoTable group by ProductName;
Kết quả:
+-------------+-------------------+ | ProductName | MAX(ProductPrice) | +-------------+-------------------+ | Product-1 | 88 | | Product-2 | 102 | | Product-3 | 90 | +-------------+-------------------+
Giải thích:
GROUP BY ProductName: Tạo 3 nhóm: Product-1, Product-2, Product-3MAX(ProductPrice): Tìm giá cao nhất trong mỗi nhóm- Product-1: max(56,88,45) = 88
- Product-2: max(78,86,102) = 102
- Product-3: max(90,59) = 90
Cách này áp dụng cho: giá cao nhất mỗi sản phẩm, điểm cao nhất mỗi học sinh, lương cao nhất mỗi phòng ban, v.v.