Natural sort with SQL Server

允我心安 提交于 2019-11-28 10:37:17

问题


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


回答1:


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)



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/14700770/natural-sort-with-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!