如何获取最大版本记录?

时间:2011-05-05 08:06:59

标签: sql sql-server tsql

我有一张如下表格:

------------------------------------
Id   FId   UId   Version
1    1     1     1
2    1     2     1
3    1     3     1
4    1     2     2
5    1     3     2
6    1     3     2
7    1     4     2
8    2     1     1
9    2     2     1

然后我希望结果是:

--------------------------
FId  UId   Version
1    2     2
1    3     2
1    4     2
2    1     1
2    2     1

如何根据每个FId-UId对的最大'版本'编写查询?

4 个答案:

答案 0 :(得分:4)

以下给出了请求的输出。

select distinct t2.FId, t2.UId, t2.Version
from
(
    select FId, max(Version) as "Version"
    from MyTable
    group by FId
) t1
inner join MyTable t2 on (t1.FId = t2.FId and t1.Version = t2.Version)
order by t2.FId, t2.UId

答案 1 :(得分:1)

select FId, UId, Version 
from MyTable
join (select Fid, Max(Version) as MaxVersion group by Fid) x 
on x.FId = MyTable.FId and x.MaxVersion = MyTable.Version

答案 2 :(得分:1)

这适用于SQL 2005及更高版本:

DECLARE @t TABLE
(Id INT,
Fid INT,
[uid] INT,
[VERSION] INT
)

INSERT @t
SELECT 1,1,1,1
UNION ALL SELECT 2,1,2,1
UNION ALL SELECT 3,1,3,1
UNION ALL SELECT 4,1,2,2
UNION ALL SELECT 5,1,3,2
UNION ALL SELECT 6,1,3,2
UNION ALL SELECT 7,1,4,2
UNION ALL SELECT 8,2,1,1
UNION ALL SELECT 9,2,2,1

;WITH myCTE
AS
(
    SELECT *,
           RANK() OVER (PARTITION BY Fid
                        ORDER BY [VERSION] DESC
                       ) AS rnk
    FROM @t
)
SELECT DISTINCT Fid, [uid],[VERSION]
FROM myCTE
WHERE rnk = 1
ORDER BY Fid, [uid]

答案 3 :(得分:0)

您显示的结果是否正确 - 1,3,2应该出现两次。如果您只需要使用一次,请选择不同的

foll查询正在运行

with t as(
select 1 as id,   1 as fid  ,  1  as uid,   1 as version union all
select 2 ,   1 ,    2 ,    1  union all
select 3 ,   1  ,   3 ,    1  union all
select 4 ,   1 ,    2   ,  2  union all
select 5  ,  1  ,   3  ,   2  union all
select 6 ,   1  ,   3  ,  2  union all
select 7 ,   1 ,    4  ,   2  union all
select 8  ,  2  ,   1  ,   1  union all
select 9 ,   2  ,   2  ,   1)

select distinct t.fid,t.uid,t.version from t 
inner join(
select fid,max(version) as maxversion from t
group by fid)as grp
on t.fid=grp.fid 
and t.version=grp.maxversion