Sort string as number in sql server

前端 未结 9 1483
不知归路
不知归路 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:40

    Plenty of good answers here, but I think this one might be the most compact order by clause that is effective:

    SELECT *
    FROM Invoice
    ORDER BY LEFT(InvoiceId,CHARINDEX('-',InvoiceId+'-'))
             ,CAST(RIGHT(InvoiceId,CHARINDEX('-',REVERSE(InvoiceId)+'-'))AS INT)DESC
    

    Demo: - SQL Fiddle

    Note, I added the '790709' version to my test, since some of the methods listed here aren't treating the no-suffix version as lesser than the with-suffix versions.

    If your invoiceID varies in length, before the '-' that is, then you'd need:

    SELECT *
    FROM Invoice
    ORDER BY CAST(LEFT(list,CHARINDEX('-',list+'-')-1)AS INT)
             ,CAST(RIGHT(InvoiceId,CHARINDEX('-',REVERSE(InvoiceId)+'-'))AS INT)DESC
    

    Demo with varying lengths before the dash: SQL Fiddle

提交回复
热议问题