Select 最高 'version' 类型 'x' 的所有记录
Select all records of type 'x' that are the highest 'version'
给定 table:
Agreement:
id: int
type: string
version: int
给出的记录如下:
1 | Terms | 1
2 | Terms | 2
3 | Privacy | 1
我想要一个输出的查询:
2 | Terms | 2
3 | Privacy | 1
我已经尝试了各种不同的和自连接到 max(version) 的方式,我似乎无法破解它。
它应该有效:
select max(id) , type , max(version) from Agreement
group by type
最简单的方法可能是使用 rank
window 函数:
SELECT id, type, version
FROM (SELECT id, type, version,
RANK() OVER (PARTITION BY type ORDER BY version DESC) AS rk
FROM agreement) t
WHERE rk = 1
试试这个:
SELECT a.id, a.type, a.version
FROM Agreement AS a
INNER JOIN (SELECT type, MAX(version) AS maxV
FROM Agreement
GROUP BY type) t
ON t.type = a.type AND a.version = t.maxV
此查询使用派生的 table,其中包含每个 type
的 MAX(version)
。加入这个派生的 table 我们可以获得原始 table 的所有行,每个 type
.
具有最大版本
PostgreSQL:
select * from agreement a where id in (select id from agreement b where a.type=b.type order by id desc limit 1)
结果:
2 |条款 | 2
3 |隐私 | 1
给定 table:
Agreement:
id: int
type: string
version: int
给出的记录如下:
1 | Terms | 1
2 | Terms | 2
3 | Privacy | 1
我想要一个输出的查询:
2 | Terms | 2
3 | Privacy | 1
我已经尝试了各种不同的和自连接到 max(version) 的方式,我似乎无法破解它。
它应该有效:
select max(id) , type , max(version) from Agreement
group by type
最简单的方法可能是使用 rank
window 函数:
SELECT id, type, version
FROM (SELECT id, type, version,
RANK() OVER (PARTITION BY type ORDER BY version DESC) AS rk
FROM agreement) t
WHERE rk = 1
试试这个:
SELECT a.id, a.type, a.version
FROM Agreement AS a
INNER JOIN (SELECT type, MAX(version) AS maxV
FROM Agreement
GROUP BY type) t
ON t.type = a.type AND a.version = t.maxV
此查询使用派生的 table,其中包含每个 type
的 MAX(version)
。加入这个派生的 table 我们可以获得原始 table 的所有行,每个 type
.
PostgreSQL:
select * from agreement a where id in (select id from agreement b where a.type=b.type order by id desc limit 1)
结果:
2 |条款 | 2
3 |隐私 | 1