16. 窗口函数 (Window Function) 的使用

从SQL Server 2005起,SQL Server开始支持窗口函数 (Window Function),以及到SQL Server 2012,窗口函数功能增强,目前为止支持以下几种窗口函数:

1. 排序函数 (Ranking Function) ;

2. 聚合函数 (Aggregate Function) ;

3. 分析函数 (Analytic Function) ;

4. NEXT VALUE FOR Function, 这是给sequence专用的一个函数;

 

. 排序函数(Ranking Function)

帮助文档里的代码示例很全。排序函数的ROW_NUMBER()较为常用,可用于去重、分页、分组中选择数据,生成数字辅助表等等;

排序函数在语法上要求OVER子句里必须含ORDER BY,否则语法不通过,对于不想排序的场景可以这样变通;

drop table if exists test_ranking create table test_ranking ( id int not null, name varchar(20) not null, value int not null ) insert test_ranking select 1,'name1',1 union all select 1,'name2',2 union all select 2,'name3',2 union all select 3,'name4',2 select id , name, ROW_NUMBER() over (PARTITION by id ORDER BY name) as num from test_ranking select id , name, ROW_NUMBER() over (PARTITION by id) as num from test_ranking /* Msg 4112, Level 15, State 1, Line 1 The function 'ROW_NUMBER' must have an OVER clause with ORDER BY. */ --ORDERY BY后面给一个和原表无关的派生列 select id , name, ROW_NUMBER() over (PARTITION by id ORDER BY GETDATE()) as num from test_ranking select id , name, ROW_NUMBER() over (PARTITION by id ORDER BY (select 0)) as num from test_ranking

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzyxzj.html