我有一个跟踪文件版本历史记录的表,并希望构建一个查询来报告每个文件的最新版本。
当前表格结构:
fileID fileName fileVersion
1 fileA 1.0.0
2 fileB 1.0.0
3 fileA 1.0.1
4 fileC 1.0.0
5 fileC 1.0.0
6 fileA 1.0.2
我想要的是什么:
fileID fileName fileVersion currentVersion
1 fileA 1.0.0
2 fileB 1.0.0 current
3 fileA 1.0.1
4 fileC 1.0.0
5 fileC 1.0.1 current
6 fileA 1.0.2 current
较旧的文件版本可以为NULL,也可以使用不同的字符串(旧版,旧版等)列出。
我能够使用MAX(Version)构建一个子查询来列出当前版本,并尝试在带有Exists或In的CASE语句中使用它来创建新列,但无法使其工作。
Select t.*,
CASE When t.fileID Exists (sub query) Then 'current' Else NULL End As currentVersion
From t
基本上,我可以返回所有结果,我可以单独返回最近的版本,但我正在寻找有关如何一起使用这两个查询来创建currentVersion列的帮助。
答案 0 :(得分:0)
您可以使用窗口函数Row_Number()
Declare @YourTable table (FileID int,fileName varchar(50),fileVersion varchar(50) )
Insert Into @YourTable values
(1,'fileA','1.0.0'),
(2,'fileB','1.0.0'),
(3,'fileA','1.0.1'),
(4,'fileC','1.0.0'),
(5,'fileC','1.0.1'),
(6,'fileA','1.0.2')
Select *
,currentVersion_A =case when Row_Number() over (Partition By FileName Order by FileID desc) = 1 then 'Current' else '' end
,currentVersion_B =case when Row_Number() over (Partition By FileName Order by FileVersion desc) = 1 then 'Current' else '' end
,currentVersion_C =case when Row_Number() over (Partition By FileName Order by Cast(ParseName(FileVersion,3 ) as Int) desc,Cast(ParseName(FileVersion,2) as Int) desc,Cast(ParseName(FileVersion,1) as Int) desc) = 1 then 'Current' else '' end
from @YourTable
Order by FileID
-- You have 3 options on how to determine Current (you know your data better than we do)
-- Use currentVersion_A IF FileID is an Identity() and each new version is added to the table
-- Use currentVersion_B IF and ONLY IF version will be 0 and 9
-- Use currentVersion_C As suggested by @HABO which is SMARTER provided the pattern is consistent
返回
FileID fileName fileVersion currentVersion
1 fileA 1.0.0
2 fileB 1.0.0 Current
3 fileA 1.0.1
4 fileC 1.0.0
5 fileC 1.0.1 Current
6 fileA 1.0.2 Current