日期:2014-05-17  浏览次数:20636 次

sql 数字与字符串 混合排序 求指教~~~~~~~
数据表 tbProductData
字段 CardCode 
数据 1,10,11,12,2,20,22,3,30,W2,W3 <直接按字段排序结果>
排序 1,2,3,10,11,12,20,22,30,W3,W4 <最后结果>
问题1: 想了2个方法,没这样用过,不知道怎样可以不?
问题2: 还有其他方法? 

--方法1:
--还是字符串的排序,有W的排最后,Len() 长度比较,当出现W时,增加其长度保证其长度能排到最后
Select * From tbProductData
where tbProductData.ListID='5EF8D369-B15E-4837-BE13-F589960B895E' 
and tbProductData.SectionNo='14'
Order By 
Len
(
Case 
When tbProductData.CardCode Like 'W%' then tbProductData.CardCode+'撑长度撑长度'
else tbProductData.CardCode
end 
),tbProductData.CardCode

--方法2:
--数字排序,格式转换,当出现W时 转换成 999999 保证起比其他数字大能排到最后
Select * From tbProductData
where tbProductData.ListID='5EF8D369-B15E-4837-BE13-F589960B895E' 
and tbProductData.SectionNo='14'
Order By 
Convert(int,
(
Case 
When tbProductData.CardCode Like 'W%' then '999999'
else tbProductData.CardCode
end 
)),tbProductData.CardCode



------解决方案--------------------
問題一:你的兩種方法都可以~(如果只有前面第一位字符是'W'的情況下)
問題二:
SQL code

select CardCode from 
(select CardCode,replace(tbProductData.CardCode,'W','999999') as tmp from tbProductData ) as a
order by cast(tmp as int) 
--也是如果只有前面第一位字符是'W'的情況下

------解决方案--------------------
SQL code



create table tbProductData
(
CardCode varchar(50)
)
insert into tbProductData values('1')
insert into tbProductData values('10')
insert into tbProductData values('11')
insert into tbProductData values('12')
insert into tbProductData values('2')
insert into tbProductData values('20')
insert into tbProductData values('22')
insert into tbProductData values('3')
insert into tbProductData values('30')
insert into tbProductData values('w2')
insert into tbProductData values('w3')
 
select CardCode from (select CardCode,replace(tbProductData.CardCode,'W','9999999') as tmp from tbProductData ) as a
order by cast(tmp as int) 


CardCode
--------------------------------------------------
1
2
3
10
11
12
20
22
30
w2
w3

(11 行受影响)

------解决方案--------------------
借用6楼数据:
SQL code
create table tbProductData
(
CardCode varchar(50)
)
insert into tbProductData values('1')
insert into tbProductData values('10')
insert into tbProductData values('11')
insert into tbProductData values('12')
insert into tbProductData values('2')
insert into tbProductData values('20')
insert into tbProductData values('22')
insert into tbProductData values('3')
insert into tbProductData values('30')
insert into tbProductData values('w2')
insert into tbProductData values('w3')
go
select * from tbProductData
order by (case when charindex('w',CardCode)>0 then REPLACE(cardcode,'w','')+999999 else CONVERT(int,cardcode) end)
/*
CardCode
--------------------------------------------------
1
2
3
10
11
12
20
22
30
w2
w3

(11 行受影响)

*/
go
drop table tbproductdata