开发者

Sorting in datatable

I have a list of records in database class

D1.1: First
D2.12: second
D1.14: third
D2.8: fourth
D2.2: fifth
D2.3: fifth
D1.7: fifth
D2: fifth
D1.5: fifth

How should I sort by taking the consideration the codes of D like 1.1, 2.12. 1.14 etc ?

The outpu开发者_如何学JAVAt required should be below.

D1.1: First  
D1.14: third  
D1.5: fifth
D1.7: fifth    
D2: fifth
D2.12: second
D2.2: fifth
D2.3: fifth
D2.8: fourth


Not clear exactly from your post how the data is in the actual table, but if it's in the field formatted like that then you could order it by using SUBSTRING. Here's an example:

DECLARE @test AS TABLE (
data varchar(50)
)

INSERT @test VALUES ('D1.1: First')
INSERT @test VALUES ('D2.12: second')
INSERT @test VALUES ('D1.14: third')
INSERT @test VALUES ('D2.8: fourth')
INSERT @test VALUES ('D2.2: fifth')
INSERT @test VALUES ('D2.3: fifth')
INSERT @test VALUES ('D1.7: fifth')
INSERT @test VALUES ('D2: fifth')
INSERT @test VALUES ('D1.5: fifth')

SELECT data FROM @test
ORDER BY SUBSTRING(data,2,CHARINDEX(':',data,0)-2)

Result:

data
--------------------------------------------------
D1.1: First
D1.14: third
D1.5: fifth
D1.7: fifth
D2: fifth
D2.12: second
D2.2: fifth
D2.3: fifth
D2.8: fourth
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜