2011-05-05 98 views
1

我有一個表,如下所示:如何獲取最大版本記錄?

------------------------------------ 
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對「版本」編寫查詢?

+1

爲什麼不是結果一行'FId = 1; UID = 1; Version = 1'在輸出? – 2011-05-05 08:27:37

回答

3

下面給出要求的輸出。

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
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 
+0

您的子查詢缺少表名稱和分組依據... – 2017-06-14 04:43:04

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] 
0

是告訴你正確─1,3,2應該出現twice.If你只需要使用一次選擇不同

的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