SQL - 如何排序值为1.4.2的字段

时间:2016-09-07 14:11:35

标签: sql sql-server sql-order-by

如何通过名为“sequentialOrder”的文本字段编写sql命令 值7.5.5 以便记录以

的顺序出现
    1.2.4
    2.3.8
    11.3.4

而不喜欢这个

    11.3.4         
    1.2.4
    2.3.8

1 个答案:

答案 0 :(得分:0)

您必须解析给定的版本字符串,以便在其ORDER BY语义的实现中访问其组件。有很多方法可以做到这一点。我个人试图避免使用CLR代码,因此我的建议是:使用点作为分隔符解析版本,将每个值转换为数字,将其聚合回列并使用正确的ORDER BY子句:

-- 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