Question

I want to convert the order of the values with column name PTNT_VST_CSNO from the following :

VMIP1
VMIP10
VMIP11
VMIP2
VMIP20
VMIP21
VMIP3
VMIP31
VMIP32
VMIP5
VMIP6
VMIP7
VMIP8
VMIP9
VMOP10
VMOP11
VMOP12
VMOP3
VMOP30
VMOP31
VMOP32
VMOP4
VMOP40
VMOP41
VMOP42
VMOP43
VMOP7
VMOP70
VMOP71
VMOP8
VMOP9

to:

VMIP1
VMIP2
VMIP3
VMIP5
VMIP6
VMIP7
VMIP8
VMIP9
VMIP10
VMIP11
VMIP20
VMIP21
VMIP31
VMIP32
VMOP3
VMOP4
VMOP7
VMOP8
VMOP9
VMOP10
VMOP11
VMOP12
VMOP30
VMOP31
VMOP32
VMOP40
VMOP41
VMOP42
VMOP43
VMOP70
VMOP71

I want to sort the numeric part of 'vmip' first then that of 'vmop'.. I tried a lot but failed every time. kindly help me guys to sort out the sorting problem... thank you in advance

Was it helpful?

Solution 2

After great trial, I succeeded to solve it with the following way..

SELECT ptnt_vst_csno 
FROM   table_name 
ORDER  BY Substring(ptnt_vst_csno, 1, Charindex('P', ptnt_vst_csno)), 
          CONVERT(INT, Substring(Substring(ptnt_vst_csno, 
                                 Charindex('P', ptnt_vst_csno), 
                                 Len( 
                                              ptnt_vst_csno)), 2, Len( 
                       ptnt_vst_csno))) 

OTHER TIPS

Not the fastest thing in the world, but it should get the job done:

ORDER BY CASE WHEN PTNT_VST_CSNO LIKE 'vmi%' THEN 0 ELSE 1 END
        ,CAST(replace(replace(PTNT_VST_CSNO, 'vmip', ''), 'vmop', '') as int)

the easiest way to accomplish this would be to change your numering to 3 digits.

i.e. 1 would become 001, 2 would become 002, 10 would become 010, and so on...

this would then allow you to order the data correctly.

you might want to do something like this:

SELECT
  PTNT_VST_CSNO,
  'VMIP' + CASE LEN(REPLACE(PTNT_VST_CSNO, 'VMIP', ''))
    WHEN 1 THEN '00' + REPLACE(PTNT_VST_CSNO, 'VMIP', '')
    WHEN 2 THEN '0' + REPLACE(PTNT_VST_CSNO, 'VMIP', '')
    ELSE REPLACE(PTNT_VST_CSNO, 'VMIP', '')
  END
FROM
  TableName
WHERE
  LEFT(PTNT_VST_CSNO, 4) = 'VMIP'
ORDER BY
  2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top