对于以下数据,我需要获取最新版本的记录。 在下面给出的数据中,我有两行Doc#5,项目#048和修订版0和1。我的要求是获取具有最大修订版的所有记录。 @nd示例是doc#17,其中有三个版本可用0,1和2,但要求是获取最新版本2.
Doc#| GO# | Item# |Documentationtype |Revision
1 MNY0005902 064 T-1 DWG 0
2 MNY0005902 59A Transient Study 0
3 MNY0005902 048 Mimic Panel 0
4 MNY0005902 59A Transient Study 0
5 MNY0005902 048 Mimic Pane 0
5 MNY0005902 048 Mimic Panel 1
13 MNY0005902 064 T-1 SUB 0
16 MNY0005902 064 T-1 FIO 0
17 MNY0005902 064 T-1 TR 0
17 MNY0005902 064 T-1 TR 1
17 MNY0005902 064 T-1 TR 2
输出应为
Doc#| GO# | Item# |Documentationtype |Revision
1 MNY0005902 064 T-1 DWG 0
2 MNY0005902 59A Transient Study 0
3 MNY0005902 048 Mimic Panel 0
4 MNY0005902 59A Transient Study 0
5 MNY0005902 048 Mimic Panel 1
13 MNY0005902 064 T-1 SUB 0
16 MNY0005902 064 T-1 FIO 0
17 MNY0005902 064 T-1 TR 2
答案 0 :(得分:1)
使用ROW_NUMBER()
SELECT *
FROM
(
SELECT *, R = ROW_NUMBER() OVER (PARTITION BY Doc#, Item# ORDER BY Revision DESC)
FROM yourtable
) as D
WHERE R = 1
答案 1 :(得分:1)
您可以使用公用表表达式来减少数据并仅获取最新修订,然后在您的表上选择并在内部联接到CTE上。
;WITH rows AS
(
SELECT Doc, MAX(Revision) AS Revision
FROM TheTable
GROUP BY Doc
)
SELECT TheTable.Doc, TheTable.GO, TheTable.Item, TheTable.DocumentationType, TheTable.Revision
FROM TheTable
INNER JOIN rows ON TheTable.Doc = rows.Doc AND TheTable.Revision = rows.Revision
Working SQLFiddle here,这也适用于MSSQL 2008。
答案 2 :(得分:1)
此查询应该给出预期的结果。
;WITH CTE as(
select *,row_number()over(partition by doc# order by revision desc) RID
from #docs
)
select doc#,Go#,Item#,DocumentationType,Revision from CTE where RID=1