当前位置: 首页 > 图文教程 > 数据库 > MSSQL > sql server中order by部分使用方式

MSSQL
使用SQL Server数据库嵌套子查询的方法
SQL Server SQL Agent服务使用教程小结
五种提高 SQL 性能的方法
非常不错的SQL语句学习手册实例版
SQL语言查询基础:连接查询 联合查询 代码
SQL SERVER的优化建议与方法
简单的SQL Server备份脚本代码
sql基本函数大全
SQL查询语句精华使用简要
数据库分页存储过程代码
SQL查询连续号码段的巧妙解法
sql server中千万数量级分页存储过程代码
sql2000各个版本区别总结
如何远程连接SQL Server数据库图文教程
一个SQL语句获得某人参与的帖子及在该帖得分总和
通用分页存储过程,源码共享,大家共同完善
SQL查找某一条记录的方法
使用 GUID 值来作为数据库行标识讲解
非常详细的SQL--JOIN之完全用法
收缩后对数据库的使用有影响吗?

MSSQL 中的 sql server中order by部分使用方式


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-30   浏览: 57 ::
收藏到网摘: n/a

order by常用的使用方式我就不提了

项目的需求千变万化
让我们看看下面几个怪排序需求

--先创建一个表
create table ai(
id int not null,
no varchar(10) not null
)
go

--往表中插入数据
insert into ai
 select 105,'2'
 union all
 select 105,'1'
 union all
 select 103,'1'
 union all
 select 105,'4'
go

--查询效果如下:
select * from ai
go
id          no        
----------- ----------
105         2
105         1
103         1
105         4


i.
--要求的查询结果如下
--即要求no列的数据按'4','1','2'排列
id          no        
----------- ----------
105         4
105         1
103         1
105         2

 

--解决方案1
--利用函数CHARINDEX
select * from ai
 order by charindex(no,'4,1,2')

--解决方案2,并且每组再按照id降序排列
--利用函数case
select * from ai
 order by case when no='4' then 1
        when no='1' then 2
                      when no='2' then 3
                 end,id desc

--解决方案3
--利用UNION 运算符
select * from ai
 where no='4'
union all
select * from ai
 where no='1'
union all
select * from ai
 where no='2'

ii.
--查询要求指定no='4'排第一行,其他的行随机排序
id          no        
----------- ----------
105         4
105         2
105         1
103         1

--解决方案
select * from ai
 order by case when no='4' then 1
   else 1+rand()
  end

iii.
--查询要求所有行随机排序

--解决方案
select * from ai
 order by newid()


iiii
--有一表ab有列i,其中数据如下:
i varchar(10)
a1
a10
a101
a5
p4
p41
p5


--现在要求列i中数据先按字母排序,再按数字排序
--效果如下:
a1
a5
a10
a101
p4
p5
p41

--解决方案
select * from ab
 order by left(i,1),convert(int,substring(i,2,8000))