[英]Ordering an NVARCHAR field in sql
I am using the below query to order a field in SQL 我正在使用以下查询在SQL中订购字段
Select Distinct x From t where c=1 order by x asc
X is an nvarchar column but currently the column have the below values X是nvarchar列,但当前该列具有以下值
Is there anyway to order the values to be like this: 无论如何,是否需要将值排序如下:
No Prize,1,2,3,4,5,6,7,8,9,10
无奖,1,2,3,4,5,6,7,8,9,10
In sql server 2012+ you could use try_cast
, but you will have to change the distinct
to a group by
: 在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)
For older versions you can use union: 对于较旧的版本,您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.