当前位置: 代码迷 >> Sql Server >> sql server 何如将前方是数字后面是字母的字段进行升序排列
  详细解决方案

sql server 何如将前方是数字后面是字母的字段进行升序排列

热度:29   发布时间:2016-04-24 19:49:02.0
sql server 何如将前面是数字后面是字母的字段进行升序排列
sqlserver中,有个字段有的全是数字,有的前面是数字后面是字母,比如:1,2,3,4,5,3A,1A,2A,排序后变成1,1A,2,2A,3,3A,4,5,如何实现?

------解决方案--------------------
----------------------------------------------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2013-11-21 10:47:56
-- Verstion:
--      Microsoft SQL Server 2012 - 11.0.2100.60 (X64) 
-- Feb 10 2012 19:39:15 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go 
create table [tb]([col] varchar(4))
insert [tb]
select '101A' union all
select '1' union all
select '1A' union all
select '2' union all
select '3' union all
select '100' union all
select '101' union all
select '10' union all
select '10A' union all
select '11'
--------------开始查询--------------------------
select * from [tb] ORDER BY CASE WHEN PATINDEX('%[A-Z a-z]%',col)>0 THEN  CAST(LEFT(col,PATINDEX('%[A-Z a-z]%',col)-1) AS INT)  ELSE cast(col AS int) END  ,SUBSTRING(col,PATINDEX('%[A-Z a-z]%',col),LEN(col))
----------------结果----------------------------
/* 
1
1A
2
3
10
10A
11
100
101
101A
*/


转换成数字就OK了
  相关解决方案