Pankaj
Pankaj

Reputation: 10115

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 output 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

Upvotes: 0

Views: 369

Answers (1)

Ira Rainey
Ira Rainey

Reputation: 5209

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

Upvotes: 1

Related Questions