Sort string as number in sql server

前端 未结 9 1503
不知归路
不知归路 2020-12-20 16:41

I have a column that contains data like this. dashes indicate multi copies of the same invoice and these have to be sorted in ascending order

790711
790109-1         


        
9条回答
  •  别那么骄傲
    2020-12-20 17:36

    Try this

    SELECT invoiceid FROM Invoice
    ORDER BY 
    CASE WHEN PatIndex('%[-]%',invoiceid) > 0
          THEN LEFT(invoiceid,PatIndex('%[-]%',invoiceid)-1)
          ELSE invoiceid END * 1
    ,CASE WHEN PatIndex('%[-]%',REVERSE(invoiceid)) > 0
          THEN RIGHT(invoiceid,PatIndex('%[-]%',REVERSE(invoiceid))-1)
          ELSE NULL END * 1
    

    SQLFiddle Demo

    Above query uses two case statements

    1. Sorts first part of Invoiceid 790109-1 (eg: 790709)
    2. Sorts second part of Invoiceid after splitting with '-' 790109-1 (eg: 1)

    For detailed understanding check the below SQLfiddle

    SQLFiddle Detailed Demo

    OR use 'CHARINDEX'

    SELECT invoiceid FROM Invoice
    ORDER BY 
    CASE WHEN CHARINDEX('-', invoiceid) > 0
          THEN LEFT(invoiceid, CHARINDEX('-', invoiceid)-1)
          ELSE invoiceid END * 1
    ,CASE WHEN CHARINDEX('-', REVERSE(invoiceid)) > 0
          THEN RIGHT(invoiceid, CHARINDEX('-', REVERSE(invoiceid))-1)
          ELSE NULL END * 1
    

提交回复
热议问题