我在sql server数据库中有以下表和数据。我正在尝试按[Version]
列获取数据顺序。我希望结果安排如下:
我怎样才能实现这个目标?
CREATE TABLE [dbo].[DocumentLog](
[DocID] [nvarchar](50) NOT NULL,
[Version] [nvarchar](50) NOT NULL) ON [PRIMARY]
GO
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.1');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.5');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.3');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.4');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.2');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.6');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.7');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.9');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.8');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.10');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.11');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.12');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.13');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.14');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.15');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.16');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.17');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','0.18');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','1.0');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','1.1');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','1.10');
INSERT INTO DocumentLog (DocID,[version])values('doc0001','2.0');
答案 0 :(得分:4)
这里真正的问题是你的表结构。您应该有两列(或软件版本控制模型中的四列)来保存版本信息。既然你没有这个,你必须以完全错综复杂的方式处理这个问题。由于您的数据似乎一致,因此可以使用PARSENAME。
select *
from DocumentLog
order by convert(int, PARSENAME(Version, 2))
, convert(int, PARSENAME(Version, 1))
答案 1 :(得分:1)
我认为你正在寻找类似的东西:
SELECT
*,
TRY_CAST(LEFT([version], CHARINDEX('.', [version])-1) AS int) MainVer,
TRY_CAST(RIGHT([version], LEN([version]) - CHARINDEX('.', [version])) AS int) AS SubVer
FROM DocumentLog
ORDER BY MainVer, SubVer;
对于2012年之前的SQL Server,将TRY_CAST
替换为CAST
。