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

MSSQL
SQL Server--全文本检索的应用(一)
SQL 2005的SSIS与Oracle的迁移性能
SQL优化实例:从运行30分钟到运行只要30秒
无法在SQL Server2005 Manger Studio 中录入中文的问题
SQL Artisan多表查询和统计
SQL Server数据库开发人员在应聘时经常被问到哪些问题
一个完整的SQL SERVER数据库全文索引的示例
SQL Server安全之加密术和SQL注入攻击
如何对SQL Server中的tempdb“减肥”
SQL Server 2005升级的十个步骤
如何在SQL Server开发中融入极限编程技术
SQL Server应用程序高级SQL注入(下)
SQL Server应用程序高级SQL注入(上)
SQL Server连接中的常见错误
IIS中SQL Server数据库的安全问题
SQL Server 2005区域配置和安全工具
保护 SQL Server 的十个步骤
如何利用SQL Server 2000的复制选项
SQL Server 数据库使用备份还原造成的孤立用户和对象名‘xxx’无效的错误的解决办法
SQL SERVER 2005同步复制技术的应用

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-30   浏览: 53 ::
收藏到网摘: 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))