我的sql表数据设置如下
SheetNo VersioId ColumnId Value
Sheet1 1 column1 3
Sheet1 3 column1 7
Sheet1 1 column2 A
Sheet1 1 column3 Z
Sheet1 4 column3 T
Sheet1 1 column5 R
Sheet1 2 column5 Q
我想编写一个SQL查询来转换此数据集,如下所示
SheetNo VersioId ColumnId Value
Sheet1 3 column1 7
Sheet1 1 column2 A
Sheet1 4 column3 T
Sheet1 2 column5 Q
我真正需要的是获取其最大版本ID的每个列值。有人可以帮我这个
答案 0 :(得分:2)
这可能会对您有所帮助:
select y1.* from YourTable y1
join
(select Columnid,max(versionid) versionid from YourTable
group by Columnid) as y2
on y1.Columnid = y2.Columnid and y1.versionid = y2.versionid
答案 1 :(得分:1)
基本上,从基表中获取SheetNo和ColumnId,然后交叉应用以通过VersioId获取VersioId和Value的顶部。分组结果以折叠行,并按您的喜好排序。可以使用相同的结构通过最大的某个不同列来获取其他数据。请参阅SqLFiddle example。
select A.SheetNo, B.VersioId, A.ColumnId, B.Value
from Sheets A
cross apply (
select top 1 VersioId, Value
from Sheets C
where C.SheetNo = A.SheetNo
and C.ColumnId = A.ColumnId
order by C.VersioId desc
) B
group by A.SheetNo, B.VersioId, A.ColumnId, B.Value
order by A.SheetNo, A.ColumnId