加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

关于Sqlserver窗口函数over的用法

发布时间:2020-12-12 14:34:47 所属栏目:MsSql教程 来源:网络整理
导读:个人觉得,sqlserver在2005以后推出窗口函数 Over完全是一个创举,他让很多的复杂的问题变得简单了。 既然是用法,我就不说明其他的东西,举一些例子就好了: create table OverTableTest(id int identity(1,1),--IDVal int,--值typ int,--类型)godeclare @c

个人觉得,sqlserver在2005以后推出窗口函数 Over完全是一个创举,他让很多的复杂的问题变得简单了。

既然是用法,我就不说明其他的东西,举一些例子就好了:

create table OverTableTest
(
	id int identity(1,1),--ID
	Val int,--值
	typ int,--类型
)
go
declare @cou int
set @cou=1
while @cou<50
begin
	insert into OverTableTest 
		select @cou,@cou%5+1 
	
	set @cou=@cou+1
end
go

select * from OverTableTest
/*
	通常我们会用到的是情景是:分页(row_Number)
	示例:
*/
;with mycte as
(
	select row=ROW_NUMBER() over (order by id desc),* from
	OverTableTest
)select * from mycte where row BETWEEN 10 and 20
/*
	在上面的情况下我经常用到,
	但是却一直没有追问 Over到底是做什么用的啊
*/
/*
	应用环境2 分组获取前几名
	就好像,考试了,要获取每科排名前3的同学
	SQL:
*/
;with mycte as
(
	select row=ROW_NUMBER() over (partition by typ order by val desc),* from
	OverTableTest
)select * from mycte where row<=3
/*
	在这个示例中 加上了partition by 就是进行分组统计了
	我们再来进行第三个示例:
	按照类别获取 类别数量,同时按照类别数量最多的排序
*/
select Cunt=count(0) over(partition by typ),* from
	OverTableTest  order by Cunt desc,typ,id 
-----------------------------------------------------------------
/*
	今天例子就说到这里了,运行结果 大家复制直接执行就好了
*/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读