sql server中order by部分使用方式

2016-01-29 15:48 2 1 收藏

sql server中order by部分使用方式,sql server中order by部分使用方式

【 tulaoshi.com - SQLServer 】

order by常用的使用方式我就不提了

项目的需求千变万化
让我们看看下面几个怪排序需求

--先创建一个表
create table ai(
id int not null,
no varchar(10) not null
)
go

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/sqlserver/)

--往表中插入数据
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

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/sqlserver/)


--现在要求列i中数据先按字母排序,再按数字排序
--效果如下:
a1
a5
a10
a101
p4
p5
p41

--解决方案
select * from ab
 order by left(i,1),convert(int,substring(i,2,8000))

来源:https://www.tulaoshi.com/n/20160129/1496510.html

延伸阅读
标签: SQLServer
1.在查询分析器理启动或停止SQL Agent服务 启动 use master go xp_cmdshell 'net start SQLSERVERAGENT' 停止 use master go xp_cmdshell 'net stop SQLSERVERAGENT' 将服务的启动从手工方式改为自动启动方式 exec xp_cmdshell 'scm -Action 7 -Service mssqlserver -SvcStartType 2' 直接用...
标签: SQLServer
      曾几何时,伙伴们为数据库的升级伤透了脑筋.往往程序的升级赶不上数据库的升级(版本控制的好,这也许不是什么问题,但对于很大一部分中国公司来说这是无法避免的).而有些n久以前的数据库要使用新程序的时候,数据库的升级简直就是无从下手.所以对比数据库升级的紧要性就逐渐的凸现出来.对于表和字段的升级按道理来说是...
SQL Server 6.5在安装使用时的默认配置并不能带来系统性能的最大优化,某些使用方法没有具体的说明,在具体应用过程中感觉非常不便。下面结合本人在使用中的心得,就SQL Server 6.5的一些安装使用方法作了简要介绍,各位可以针对自己的情况进行修改。 1. 安装中的要点 安装时要求系统使用Windows NT Server 4.0 ,并且加装SP4。 a)...
1.在查询分析器理启动或停止SQL Agent服务 启动 use master go xp_cmdshell 'net start SQLSERVERAGENT' 停止 use master go xp_cmdshell 'net stop SQLSERVERAGENT' 将服务的启动从手工方式改为自动启动方式 exec xp_cmdshell 's...
标签: SQLServer
建一表,放初始化资料  因为农历的日期,是由天文学家推算出来的,到现在只有到2049年的,以后的有了还可以加入!  CREATE  TABLE  SolarData  (         yearId  int  not  null,         data  char(7)  no...

经验教程

164

收藏

52
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部