sql server order by 的一些高级用法

SQL SERVER数据库中order by的一些高级用法
本文章属于转载文章,原博客地址为:https://blog.csdn.net/dieyingao/article/details/4196142

先创建一个表
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

idno
1052
1051
1031
1054

一:查询结果如下的解决方案
即要求no列的数据按’4’,’1’,’2’排列

idno
1054
1051
1031
1052

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

二:查询要求指定no=’4’排第一行,其他的行随机排序

idno
1054
1052
1051
1031

解决方案

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

三:查询要求所有行随机排序
解决方案

select * from ai 
 order by newid()

四:有一表ab有列i,其中数据如下:
i varchar(10)

idno
a1
a10
a101
a5
p4
p41
p5

现在要求列i中数据先按字母排序,再按数字排序,效果如下

i varchar(10)

idno
a1
a5
a10
a101
p4
p5
p41

a 1
a 5
a 10
a 101
p 4
p 5
p 41
解决方案

select * from ab 
 order by left(i,1),convert(int,substring(i,2,8000))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值