技术开发 频道

Sql Server2005对t-sql的增强之排名函数


【IT168技术文档】

  Sql Server2005中新增加了4个排名函数:ROW_NUMBER, RANK, DENSE_RANK, NTILE;大家一定已经对ROW_NUMBER非常熟悉了,所以我从最后一个NTILE开始分析。
  NTILE在msdn中的解释是:将有序分区中的行分发到指定数目的组中。各个组有编号,编号从一开始。对于每一个行,NTILE 将返回此行所属的组的编号。不知道大家是不是一下子就能看懂这个解释,反正我是结合解释自己写了例子才弄明白的。

  准备脚本,我们创建一个简单的3列表,三列分别是id,categoryId,和name,如下:
GO if object_id('t_ntile','U') is not null drop table t_ntile; GO create table t_ntile ( id int unique not null, categoryId int not null, name nvarchar(20) ) go INSERT INTO t_ntile VALUES(1,1,'A') INSERT INTO t_ntile VALUES(2,4,'B') INSERT INTO t_ntile VALUES(3,2,'C') INSERT INTO t_ntile VALUES(4,1,'D') INSERT INTO t_ntile VALUES(5,3,'E') INSERT INTO t_ntile VALUES(6,3,'F') INSERT INTO t_ntile VALUES(7,2,'G') INSERT INTO t_ntile VALUES(8,2,'H') INSERT INTO t_ntile VALUES(9,2,'I') Go
  查询语句如下:
SELECT id,categoryId,name ,'ntile value' = NTILE(3) OVER(PARTITION BY categoryId ORDER BY categoryId) FROM t_ntile
  我们给NTITL传的参数是3,即表示一共三组,然后OVER中表达式指定要根据categoryId来分割分组,并要按照categoryId排序。上面的表达式执行结果如下:

0
相关文章