Tìm giá trị lớn nhất theo nhóm với GROUP BY và MAX()
Kỹ thuật cơ bản: GROUP BY cot_phan_nhom kết hợp MAX(cot_gia_tri).
Tạo bảng và dữ liệu
mysql> create table DemoTable (
CountryName varchar(20),
Population int
);
Query OK, 0 rows affected (0.56 sec)
mysql> insert into DemoTable values('US',560);
mysql> insert into DemoTable values('UK',10090);
mysql> insert into DemoTable values('UK',8794);
mysql> insert into DemoTable values('US',1090);
Truy vấn: Dân số lớn nhất của mỗi quốc gia
mysql> select CountryName, max(Population) from DemoTable group by CountryName;
Kết quả
+-------------+-----------------+ | CountryName | max(Population) | +-------------+-----------------+ | US | 1090 | | UK | 10090 | +-------------+-----------------+
Mở rộng - Lấy toàn bộ hàng có giá trị max (không chỉ giá trị max):
-- Cách 1: JOIN với subquery
SELECT d1.* FROM DemoTable d1
JOIN (SELECT CountryName, MAX(Population) as max_pop FROM DemoTable GROUP BY CountryName) d2
ON d1.CountryName = d2.CountryName AND d1.Population = d2.max_pop;
-- Cách 2: Window function (MySQL 8.0+)
SELECT CountryName, Population FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CountryName ORDER BY Population DESC) as rn
FROM DemoTable
) t WHERE rn = 1;
Ứng dụng: Báo cáo doanh số cao nhất từng khu vực, điểm thi cao nhất từng môn, giá cao nhất từng danh mục.