在sql中排序NVARCHAR字段

时间:2017-04-20 12:23:32

标签: sql sql-server sql-server-2008 tsql

我使用以下查询在SQL

中订购字段
download_extract:
  archive.extracted:
    - name: /opt/
    - if_missing: /opt/
    - source: {{ settings.binaries_url }}
    - source_hash: {{ settings.hash_url }}
    - user: {{ settings.env.user }}
    - group: {{ settings.env.user }}
    - enforce_ownership_on: /opt/
    - enforce_toplevel: False
    - options: --strip-components=1

X是nvarchar列,但目前该列具有以下值

enter image description here

无论如何命令值都是这样的:

  

无奖,1,2,3,4,5,6,7,8,9,10

1 个答案:

答案 0 :(得分:1)

在sql server 2012+中,你可以使用try_cast,但是你必须将distinct更改为group by

SELECT x
FROM t
WHERE c=1
GROUP BY x
ORDER BY Try_Cast(x as int) 

对于旧版本,您可以使用union:

SELECT x
FROM
(
    SELECT x, CAST(x as int) as sort
    FROM t
    WHERE c = 1
    AND ISNUMERIC(x) = 1

    UNION 

    SELECT x, NULL
    FROM t
    WHERE c = 1
    AND ISNUMERIC(x) = 0
) as distinctX
ORDER BY sort