SQL顺序由复数字符串列作为数字

时间:2016-10-20 14:18:19

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

我有一张这样的表:

| ID | Name | Code  |
---------------------
| 1  | test | 11-2  |
| 2  | test | 11/1  |
| 3  | test | 1     |
| 4  | test | 10x   |
| 5  | test | 11-11 |
| 6  | test | *     |
| 7  | test | 2     |
| 8  | test | m10   |
| 9  | test | 11-*  |
| 10 | test | 11    |
| 11 | test | 10    |

“代码”列类型为NVARCHAR。我希望通过Code获取记录,以便它们排序如下:

*
1
2
10
10x
11
11-*
11/1
11-2
11-11
m10

但简单的'按代码排序'查询会返回:

*
1
10
10x
11
11-*
11/1
11-11
11-2
2
m10

1 个答案:

答案 0 :(得分:1)

试试这个

select *,ISNUMERIC(LEFT(t,1)) as num,REPLICATE('0',10-len(t))+RTRIM(t) as ord
from(
select '11-2 ' as t union all
select '11/1 ' union all
select '1    ' union all
select '10x  ' union all
select '11-11' union all
select '*    ' union all
select '2    ' union all
select 'm10  ' union all
select '11-* ' union all
select '11   ' union all
select '10   ' 
)as p

order by num desc,ord