Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting in TSQL

I am using SQL Server 2008.

I would like to sort my result by using the DetailRefNumber. However, I could not achieve to sort like

2.1 
2.2 
2.3 
xxx
xxx
2.10
2.11
2.12

Could you please guide me how I could do it?

enter image description here Thanks.

like image 274
TTCG Avatar asked May 25 '26 04:05

TTCG


1 Answers

If that DetailRefNumber will always be a number, separated by a dot, you could add two computed columns to that table which basically take that column apart into two separate, numeric values:

alter table dbo.YourTable
  add RefNrMajor AS CAST(LEFT(DetailRefNumber, CHARINDEX('.', DetailRefNumber) - 1) AS INT) PERSISTED

alter table dbo.YourTable
  add RefNrMinor AS CAST(SUBSTRING(DetailRefNumber, CHARINDEX('.', DetailRefNumber) + 1, 999) AS INT) PERSISTED

and now you can order by those new numeric columns:

SELECT (columns)
FROM dbo.YourTable
ORDER BY RefNrMajor, RefNrMinor
like image 198
marc_s Avatar answered May 28 '26 17:05

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!