当前位置: 代码迷 >> Sql Server >> SQL 排序解决方案
  详细解决方案

SQL 排序解决方案

热度:127   发布时间:2016-04-24 08:48:02.0
SQL 排序
数据库表中列为
bytes       列中内容为
1GB
2GB
16MB
256MB
我想按bytes从小到大排序要怎么排,需要考虑到单位。

------解决思路----------------------
单位统一不就可以了.
------解决思路----------------------
SQL识别不了单位  除非你新加单位表
------解决思路----------------------


create table test (bytes varchar(30))
go
insert into test values('1GB'),('2GB'),('16MB'),('32MB'),('256MB')
go
select * , substring(bytes,1, len(bytes) - 2) , substring(bytes,len(bytes) -1,1)
 from test 
order by 
  case substring(bytes,len(bytes) -1,1) when 'G' then 3 when 'M' then 2 when 'K' then 1 end ,
  cast(substring(bytes,1, len(bytes) - 2) as decimal(18,2))
go
drop table test 
go


(5 行受影响)
bytes                                                         
------------------------------ ------------------------------ ----
16MB                           16                             M
32MB                           32                             M
256MB                          256                            M
1GB                            1                              G
2GB                            2                              G

(5 行受影响)



------解决思路----------------------
建议把单位单独立放在一列, 或者加一个系数列,就更简单了。 3NF 还是要遵循的。 
  相关解决方案