您的位置:首页 > 数据库

NTILE函数在SQL Server 2000中的实现方法

2009-08-05 13:14 302 查看
众所周知,NTILE函数是SQL Server 2005的新特性之一,用于将有序分区中的行分发到指定数目的组中。各个组有编号,编号从一开始。对于每一个行,NTILE 将返回此行所属的组的编号。如果分区的行数不能被整数整除,则将导致一个成员有两种大小不同的组。按照 OVER 子句指定的顺序,较大的组排在较小的组前面。用NTILE函数计算排名值与其它方法一样简单(分区排名方案和排名值效率分析【图文+测试代码】 ),唯一的区别在于,NTILE函数接受一个表示组的数量的参数,而其它的方法是没有参数的。

SQL代码和效果如下:

declare @numtile int;
set @numtile =9;--组数

select empid ,qty,rn,
case when rn<=(tilesize+1)*remainder
then (rn-1)/(tilesize+1)+1
else (rn-remainder-1)/(tilesize)+1
end as tiles
from
(
select empid,qty,rn,numrows/@numtile as tilesize,numrows%@numtile as remainder
from
(
select empid,qty,(select COUNT (*) from Sales as S2 where S2.qty <S1.qty or S2.qty =S1.qty and S2.empid <=S1.empid) as rn ,(select COUNT (*) from Sales ) as numrows from Sales as S1
) as D1
) as D2 order by qty,empid
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐