我有下表:
ID Revision
1 A.1
1 A.2
1 A.4
1 A
1 B.1
1 B
1 C
1 D.1
我想写一个查询来返回以下内容:
ID Revision Version
1 A.1 A.1
1 A.2 A.2
1 A.4 A.4
1 A A.5
1 B.1 B.1
1 B B.2
1 C C.1
1 D.1 D.1
寻求帮助。我的问题是我需要的版本基于以前的版本加上一个版本。
请告知。
答案 0 :(得分:0)
SELECT ID
,Revision
,Version = LEFT(Revision, 1)+'.'
+CAST(ROW_NUMBER() OVER (PARTITION BY ID, LEFT(Revision,1) ORDER BY ID, LEFT(Revision, 1), LEN(Revision) DESC, Revision) AS VARCHAR)
FROM @tbl
ORDER BY ID, LEFT(Revision, 1), LEN(Revision) DESC, Revision
这将生成您提供的结果集,但版本号不会跳过A.3
ORDER BYs如此尴尬的原因是确保始终显示没有数字的修订。
答案 1 :(得分:0)
好的,我找到了一个难看的解决方案。我加入了表格以创建当前版本和lag_revision。然后我计算了一个新的字段(版本)。我的表名是文件。
example:
ID REV LAG_REV Version
Xxx A.1 (null) A.1
Xxx A.3 A.1 A.3
Xxx A A.3 A.4
With numbered_docs as (
Select row_number() over (partition by ID order by creation_date) as rn, d.* from documents d
)
select z.ID,z.REVISION,z.lag_row_rev,z.Version into versions from (
Select d1.ID d1.revision, d2.revision as lag_row_rev,d1.CREATION_DATE
,(select case
when (CHARINDEX('.',d2.REVISION) > 0 and substring(d2.REVISION,1,CHARINDEX('.', d2.REVISION+'.')-1)=substring(d1.REVISION,1,CHARINDEX('.', d1.REVISION+'.')-1))
then (substring(d2.REVISION,1,CHARINDEX('.', d2.REVISION)) + cast((cast(SUBSTRING(d2.REVISION,CHARINDEX('.', d2.REVISION)+1,LEN(d2.revision)) as integer)+1) AS varchar))
when CHARINDEX('.',d1.REVISION) > 0 and CHARINDEX('.',d2.REVISION)=0 then substring(d1.REVISION,1,CHARINDEX('.', d1.REVISION)) + cast((cast(SUBSTRING(d1.REVISION,CHARINDEX('.', d1.REVISION)+1,LEN(d1.revision)) as integer)) AS varchar)
when d2.REVISION IS null and CHARINDEX('.',d1.REVISION) > 0 then substring(d1.REVISION,1,CHARINDEX('.', d1.REVISION)) + cast((cast(SUBSTRING(d1.REVISION,CHARINDEX('.', d1.REVISION)+1,LEN(d1.revision)) as integer)) AS varchar)
when d2.REVISION IS null and CHARINDEX('.',d1.REVISION) = 0 then d1.REVISION+'.1'
when CHARINDEX('.',d1.REVISION) = 0 and CHARINDEX('.',d2.REVISION) = 0 then d1.REVISION+'.1'
when CHARINDEX('.',d2.REVISION) > 0 and CHARINDEX('.',d1.REVISION) > 0 and substring(d2.REVISION,1,CHARINDEX('.', d2.REVISION+'.')-1)<> substring(d1.REVISION,1,CHARINDEX('.', d1.REVISION+'.')-1)
then substring(d1.REVISION,1,CHARINDEX('.', d1.REVISION)) + cast((cast(SUBSTRING(d1.REVISION,CHARINDEX('.', d1.REVISION)+1,LEN(d1.revision)) as integer)) AS varchar)
else NULL
end ) as [Version]
From numbered_docs d1
Left Join numbered_docs d2 on (d1.ID=d2_ID and d1.rn=d2.rn+1)
) z
order by z.ID,z.revision;