Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 265
  • Last Modified:

SQL Help - Varchar Sort

Team,

I have a varchar field in a table. When used in a query, i get the below results:

Age
1 - 7
15 - 21
22 - 28
29 - 35
8 - 14

This is not sorted according to the age.

it should be

Age
1 - 7
8 - 14
15 - 21
22 - 28
29 - 35


How can i achieve this in sql query?
0
davidi1
Asked:
davidi1
1 Solution
 
Imran Javed ZiaConsultant Software Engineer - .NET ArchitectCommented:
Hi,
there are following ways,

split data on - and get first part convert it to int and use it in sorting, It is difficult but you can use it with little code


Use two digit scheme so use following value
01 - 07
08 - 14
15 - 21
22 - 28
29 - 35

if there is some key value like id then use it for sorting

otherwise add some sort oder column in table

Thanks
0
 
davidi1Author Commented:
Thanks. I used 2 digit scheme.., works perfectly
0
 
tigin44Commented:
try this

ORDER BY CAST(LEFT(AGE, CHARINDEX(' ', AGE, 1)-1) AS int)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now