SQL - 查询某一字段值相同而另一字段值最大的记录

时间:2021-09-29 15:12:53

有时需要以某一字段作为分组,筛选每一组的另一字段值最大(或最小)的记录。例如,有如下表 app,存储了 app 的 ID、名称、版本号等信息。现在要筛选出每个 app 版本最大的记录。

SQL - 查询某一字段值相同而另一字段值最大的记录

 

方法一

SELECT a.* FROM app a 
WHERE a.app_version = (SELECT MAX(b.app_version) FROM app b WHERE b.app_name = a.app_name) 
ORDER BY a.app_name;

方法二

SELECT a.* FROM app a
WHERE NOT EXISTS(SELECT 1 FROM app b WHERE b.app_name = a.app_name AND b.app_version > a.app_version)
ORDER BY a.app_name;

方法三

SELECT a.* 
FROM app a, (SELECT app_name, MAX(app_version) AS app_version FROM app GROUP BY app_name) b
WHERE a.app_name = b.app_name
AND a.app_version = b.app_version
ORDER BY a.app_name;

方法四

SELECT a.* 
FROM app a INNER JOIN (SELECT app_name, MAX(app_version) AS app_version FROM app GROUP BY app_name) b
ON a.app_name = b.app_name
AND a.app_version = b.app_version
ORDER BY a.app_name;