我有一个数据库表,其中包含(针对此问题)三列:
每个文档都有1..n版本,每个版本都有1..n版本。
对于所有文档的最高修订版和最高版本,我的SQL语句是什么?
Doc Title Revision Version Should be selected
Dok 1 01 01
Dok 1 01 02
Dok 1 01 03
Dok 1 02 01
Dok 1 02 02 * Because Rev 02 / V02 is the highest
Dok 2 01 01
Dok 2 02 01
Dok 2 03 01 * Because Rev 03 / V01 is the highest
D
答案 0 :(得分:2)
如果您为每个行(我为所有表建议)都具有唯一的ID,那么可以使用相关子查询:
select d.*
from documents as d
where d.pk = (select top (1) d2.pk
from documents as d2
where d2.documentid = d.documentid
order by d2.version desc, d2.revision desc, d2.pk desc
);
没有主键,您可以通过将值连接在一起来实现:
select d.*
from documents as d
where d.version & "-" & d.revision =
(select top (1) d2.version & "-" & d2.revision
from documents as d2
where d2.documentid = d.documentid
order by d2.version desc, d2.revision desc
);
答案 1 :(得分:0)
您可以使用最大聚合函数并通过与子查询结合使用
select id, max_ver, max(revision)
from my_table m
inner join (
select ID, max(version) max_ver
from my_table
group by id
) t on t.id = m.id and t.max_ver = m.version
group by id, max_ver
答案 2 :(得分:0)
假设表名为Table1
(更改为适合),我建议如下:
SELECT
Table1.[Document ID],
Table1.Revision,
Max(Table1.Version) As Version
FROM
Table1 INNER JOIN
(
SELECT
Table1.[Document ID],
Max(Table1.Revision) AS Rev
FROM
Table1
GROUP BY
Table1.[Document ID]
) DocRev
ON
Table1.[Document ID] = DocRev.[Document ID] AND
Table1.Revision = DocRev.Rev
GROUP BY
Table1.[Document ID],
Table1.Revision
在这里,嵌套的SELECT
查询首先为每个Revision
获得最大的Document ID
:
SELECT
Table1.[Document ID],
Max(Table1.Revision) AS Rev
FROM
Table1
GROUP BY
Table1.[Document ID]
然后将其INNER JOIN
绑定到原始表,以获取每个最大Version
的所有Revision
记录,最终将最大Version
个记录输出到结果。 / p>