VAR字符列上的SQL字母数字排序

时间:2016-10-18 00:19:08

标签: sql sql-server sorting alphanumeric

我正在处理需要按字母排序然后按数字排序的字母数字列值。

数据示例:

  • a1
  • A10
  • a11
  • AB2
  • AB21
  • ab22
  • A1A
  • A1B

需要按如下方式排序:

  • A1
  • A1A
  • A1B
  • A2
  • A3
  • AB1
  • AB2
  • AB3
  • ...

需要有关如何在SQL中对此进行排序的建议。

感谢。

2 个答案:

答案 0 :(得分:1)

以下内容可能适用于字母数字。但是请注意,对于非字母数字值,行为未定义。

WITH A (A, N) AS (
    SELECT A, 3 + LEN(A) FROM (
        SELECT 'a1'
        UNION ALL
        SELECT 'a10'
        UNION ALL
        SELECT 'a11'
        UNION ALL
        SELECT 'ab2'
        UNION ALL
        SELECT 'ab21'
        UNION ALL
        SELECT 'ab22'
        UNION ALL
        SELECT 'a1a'
        UNION ALL
        SELECT 'a1b'
        UNION ALL
        SELECT 'a1'
        UNION ALL
        SELECT 'a1a'
        UNION ALL
        SELECT 'a1b'
        UNION ALL
        SELECT 'a2'
        UNION ALL
        SELECT 'a3'
        UNION ALL
        SELECT 'a9'
        UNION ALL
        SELECT 'ab1'
        UNION ALL
        SELECT 'ab2'
        UNION ALL
        SELECT 'ab3'
    ) T (A)
), B (A, N, I, C, D, X) AS (
    SELECT A, N, 3, CAST(SUBSTRING(A, 1, 1) AS VARCHAR(255)), CAST(SUBSTRING(A, 2, 1) AS VARCHAR(255)), CAST('' AS VARCHAR(255)) FROM A
    UNION ALL
    SELECT A, N, I + 1, D, CAST(SUBSTRING(A, I, 1) AS VARCHAR(255)), CASE WHEN ASCII(C) BETWEEN 48 AND 57 AND ASCII(D) BETWEEN 48 AND 57 THEN CAST(X + CHAR(10 + ASCII(D)) AS VARCHAR(255)) WHEN 58 > ASCII(C) THEN CAST(X + C AS VARCHAR(255)) ELSE CAST(X + CHAR(3 + ASCII(C)) AS VARCHAR(255)) END FROM B WHERE I <= N
)
SELECT A FROM B WHERE I = N
ORDER BY X COLLATE Latin1_General_BIN

代码目前以区分大小写的方式排序,但也可以调整以进行不区分大小写的排序,例如使用

ORDER BY UPPER(X) COLLATE Latin1_General_BIN

ORDER BY LOWER(X) COLLATE Latin1_General_BIN

答案 1 :(得分:0)

你试过吗?

SELECT column_x
FROM table_name x
ORDER BY x.column_name ASC|DESC, x.column_name ASC|DESC;