首 页资讯中心软件分类
您当前的位置:it66.net 爱特下载站资讯中心数据库类 → 文章内容 退出登录 用户管理
本类热门文章
相关内容
sql server中order by部分使用方式
作者:佚名  来源:不详  发布时间:2007-9-23 0:24:02

减小字体 增大字体

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))

[] [返回上一页] [打 印]
相关文章
评论
(评论内容只代表网友观点,与本站立场无关!)

用户名: 查看更多评论

分 值:100分 85分 70分 55分 40分 25分 10分 0分

内 容:

         (注“”为必填内容。) 验证码: 验证码,看不清楚?请点击刷新验证码

软件发布 - 广告合作 - 下载声明 - 友情连接 - 申请连接 - 网站地图 - 管理登陆