SQL 获取 distinct、max 和 id

SQL getting distinct, max, and id

我有一个名为 versions 的 table,我正在尝试获取 ID、正文和最高版本。我正在使用 Postgres

当我使用

SELECT DISTINCT(body), MAX(version) FROM versions
WHERE body = 'Maintain records of all disclosures'
GROUP BY body

我明白了

当我尝试添加 id

SELECT DISTINCT(body), MAX(version), id  FROM versions
WHERE body = 'Maintain records of all disclosures'
GROUP BY body, id

我明白了

我需要更改什么才能只获取 max 最高的 id?

https://www.sqlservercentral.com/articles/eliminating-duplicate-rows-using-the-partition-by-clause

WITH DATA AS (

SELECT BODY, 
       ID,
       MAX(version) OVER(PARITION BY BODY ORDER BY ID) AS MAX_VERSION,
       ROW_NUMBER() OVER(PARTITION BY BODY ORDER BY ID) AS ROW_NUM

FROM versions
WHERE body = 'Maintain records of all disclosures'

)

SELECT 
*
FROM DATA
WHERE ROW_NUM = 1

你可以这样做:

SELECT body, version, id 
FROM versions 
WHERE version = (
 SELECT MAX(version) 
  FROM versions 
  WHERE body = 'Maintain records of all disclosures') 
AND body = 'Maintain records of all disclosures'

如果我没理解错的话,你想要distinct on:

SELECT DISTINCT ON (v.body), v.*
FROM versions v
WHERE v.body = 'Maintain records of all disclosures'
ORDER BY body, version DESC;

但是,如果结果集中只需要一行,LIMIT 就足够了:

SELECT v.*
FROM versions v
WHERE v.body = 'Maintain records of all disclosures'
ORDER BY body, version DESC
LIMIT 1;