Natural sort with SQL Server

删除回忆录丶 提交于 2019-11-29 16:39:43

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
Debs

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