风舞残阳 2008-4-2 17:54
sql server中order by部分使用方式
[size=3][/size]orderby常用的使用方式我就不提了
项目的[wiki]需求[/wiki]千变万化
让我们看看下面几个怪排序需求
--先创建一个表
createtableai(
idintnotnull,
novarchar(10)notnull
)
go
--往表中插入数据
insertintoai
select105,'2'
unionall
select105,'1'
unionall
select103,'1'
unionall
select105,'4'
go
--查询效果如下:
select*fromai
go
idno
---------------------
1052
1051
1031
1054
i.
--要求的查询结果如下
--即要求no列的数据按'4','1','2'排列
idno
---------------------
1054
1051
1031
1052
--解决方案1
--利用函数CHARINDEX
select*fromai
orderbycharindex(no,'4,1,2')
--解决方案2,并且每组再按照id降序排列
--利用函数case
select*fromai
orderbycasewhenno='4'then1
whenno='1'then2
whenno='2'then3
end,iddesc
--解决方案3
--利用UNION运算符
select*fromai
whereno='4'
unionall
select*fromai
whereno='1'
unionall
select*fromai
whereno='2'
ii.
--查询要求指定no='4'排第一行,其他的行随机排序
idno
---------------------
1054
1052
1051
1031
--解决方案
select*fromai
orderbycasewhenno='4'then1
else1+rand()
end
iii.
--查询要求所有行随机排序
--解决方案
select*fromai
orderbynewid()
iiii
--有一表ab有列i,其中数据如下:
ivarchar(10)
a1
a10
a101
a5
p4
p41
p5
--现在要求列i中数据先按字母排序,再按数字排序
--效果如下:
a1
a5
a10
a101
p4
p5
p41
--解决方案
select*fromab
orderbyleft(i,1),convert(int,substring(i,2,8000))