how would you write sql to order by a text field called "sequentialOrder" with values like 7.5.5 so that the records come out in the order of
1.2.4
2.3.8
11.3.4
and not like this
11.3.4
1.2.4
2.3.8
how would you write sql to order by a text field called "sequentialOrder" with values like 7.5.5 so that the records come out in the order of
1.2.4
2.3.8
11.3.4
and not like this
11.3.4
1.2.4
2.3.8
You have to parse the given version strings to access its components a implement its ORDER BY
semantics. There are many ways to do it. I personally try to avoid CLR code, so here comes my suggestion: parse the version using the dot as separator, convert each value to number, aggregate it back into columns and use a proper ORDER BY
clause:
-- this script uses the function [dbo].[DelimitedSplit8K] to split a delimited
-- string value into multiple rows; it was published and is avalable at
-- http://www.sqlservercentral.com/articles/Tally+Table/72993/
-- setup
CREATE TABLE version (id VARCHAR(20))
INSERT version (id) VALUES('1.2.4');
INSERT version (id) VALUES('2.3.8');
INSERT version (id) VALUES('11.3.4');
-- cte query
; WITH inrows AS (
-- split version ID into many rows
SELECT ver.id, dlm.itemNumber, CONVERT(INT, dlm.item) as item
FROM version ver
CROSS APPLY [dbo].[DelimitedSplit8K](ver.id, '.') dlm
)
, inCols AS (
-- aggregate the rows groupped by id
SELECT inr.id
, MAX(CASE WHEN inr.itemNumber = 1 THEN inr.item ELSE NULL END) AS [major]
, MAX(CASE WHEN inr.itemNumber = 2 THEN inr.item ELSE NULL END) AS [minor]
, MAX(CASE WHEN inr.itemNumber = 3 THEN inr.item ELSE NULL END) AS [revision]
FROM inrows inr
GROUP BY inr.id
)
SELECT *
FROM inCols inc
ORDER BY inc.major, inc.minor, inc.revision;
-- RESULTS ================================================
-- id major minor revision
-- -------------------- ----------- ----------- -----------
-- 1.2.4 1 2 4
-- 2.3.8 2 3 8
-- 11.3.4 11 3 4