SQL - 查詢某一字段值相同而另外一字段值最大的記錄

有時須要以某一字段做爲分組,篩選每一組的另外一字段值最大(或最小)的記錄。例如,有以下表 app,存儲了 app 的 ID、名稱、版本號等信息。如今要篩選出每一個 app 版本最大的記錄。app

 

方法一spa

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;

方法二code

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;

方法三blog

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;

方法四io

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;
相關文章
相關標籤/搜索