Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
NguyenL71
Posting Yak Master
228 Posts |
Posted - 2014-02-11 : 13:06:05
|
I need to order data by the desired output below but can't get it to work now. Any help is appreciated. Please see the desired output below. Basically,I need to Sort VSQL5, 6, 7,.... 10, 11,SQL 2012Thank you.IF OBJECT_ID('Tempdb.dbo.#Test', 'u') IS NOT NULL DROP TABLE #TestGOCREATE TABLE #Test( Srvname VARCHAR(20) NULL)GOINSERT #test VALUES ('All'), ('VCUS3RCA'), ('VCUS4RCA'), ('VCUS5RCA'),('VCUS6RCA'),('VSQL10'), ('VSQL11'), ('VSQL12'), ('VSQL13'), ('VSQL14'), ('VSQL15'),('VSQL16'), ('VSQL17'),('VSQL18'), ('VSQL4'), ('VSQL5'), ('VSQL6'), ('VSQL7'), ('VSQL8'),('VSQL9'), ('VSQL3');SELECT * FROM #Test;-- Desired Results:Srvname--------------------Srvname--------------------AllVCUS3RCAVCUS4RCAVCUS5RCAVCUS6RCAVSQL3VSQL4VSQL5VSQL6VSQL7VSQL8VSQL9VSQL10VSQL11VSQL12VSQL13VSQL14VSQL15VSQL16VSQL17VSQL18--Testing SELECT *, Row_Number() over(order by Srvname ASC) FROM #Test ORDER BY Row_Number() over(order by Srvname ASC) |
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2014-02-11 : 14:41:04
|
That is ugly. They would sort naturally if the [SrvName] number suffixes had leading zeros like VSQL002.This expression does that. It's not pretty but there's no "good" way.order by case when SrvName like 'VSQL%' then 'VSQL' + replace(str(replace(Srvname, 'VSQL',''), 3),' ','0') else SrvName end Actually the right way would be to create a mapping table that has SrvName and SortOrder. Join by SrvName and Order by SortOrder.Be One with the OptimizerTG |
|
|
NguyenL71
Posting Yak Master
228 Posts |
Posted - 2014-02-11 : 17:32:14
|
Thank you for suggestions.quote: Originally posted by TG That is ugly. They would sort naturally if the [SrvName] number suffixes had leading zeros like VSQL002.This expression does that. It's not pretty but there's no "good" way.order by case when SrvName like 'VSQL%' then 'VSQL' + replace(str(replace(Srvname, 'VSQL',''), 3),' ','0') else SrvName end Actually the right way would be to create a mapping table that has SrvName and SortOrder. Join by SrvName and Order by SortOrder.Be One with the OptimizerTG
|
|
|
|
|
|
|
|