现在的位置: 首页 > 综合 > 正文

表中记录查询排序随笔(sql server中order by使用方式小总结)

2011年10月08日 ⁄ 综合 ⁄ 共 1440字 ⁄ 字号 评论关闭

相关文章导航
  1. Sql Server2005 Transact-SQL 新兵器学习总结之-总结
  2. Flex,Fms3相关文章索引
  3. FlexAir开源版-全球免费多人视频聊天室,免费网络远程多人视频会议系统((Flex,Fms3联合开发))<视频聊天,会议开发实例8>

跟DB打交道,用得最多的是查询,既然查询就会有查询记录排序问题,我一直通过order by来解决,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
--利用函数case
select * from ai
 order by case when no='4' then 1
        when no='1' then 2
                      when no='2' then 3
                 end

--解决方案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))

 

希望上面提到的知识对你有所提示

当然欢迎交流和指正

 

 

 

 

收藏与分享

收藏到QQ书签 添加到百度搜藏 添加到百度搜藏 添加到雅虎收藏 分享到饭否 收藏到就喜欢网络收藏夹

RSS订阅我 什么是RSS?

feedsky   http://wap.feedsky.com/aierongrss   E-mail
订阅到雅蛙      使用RSS邮天下订阅   订阅到有道阅读
订阅到抓虾   鲜果阅读器订阅图标   Add to Google
訂閱 Bloglines   哪吒提醒   Subscribe in NewsGator Online

东莞.net俱乐部

东莞.net俱乐部 欢迎您的加入

抱歉!评论已关闭.