为了创建更线性的分布,我在数据表中添加了一个计算列,点击
HITS_SQRT AS (CONVERT([int],sqrt(HITS*4),(0))) PERSISTED
.
使用此列,您可以计算“按百分比点击”的目标数量。
select @hitsPerGroup=SUM(HITS_SQRT)/(@numGroups -1)-@numGroups, @dataPoints=COUNT(*) FROM #Rank_Table
然后,该脚本创建一个临时表,该表的行_number()按点击数排序,并按降序迭代这些行,将其百分位数从100更新为1。一个连续的总命中数被保存,当
@hitsPerGroup
通过后,百分比从100降低到99、99降低到98等。
然后,源数据表用它的百分比更新。有一个临时工作表的索引来加速更新。
完整脚本使用
#Rank_Table
作为源数据表。
--Create Test Data
CREATE TABLE #Rank_Table(
id int identity(1,1) not null,
hits bigint not null default 0,
PERCENTILE smallint NULL,
HITS_SQRT AS (CONVERT([int],sqrt(HITS*4),(0))) PERSISTED
)
--Slant the distribution of the data
INSERT INTO #Rank_Table (hits)
select CASE
when DATA > 9500 THEN DATA*30
WHEN data > 8000 THEN DATA*5
WHEN data < 7000 THEN DATA/3 +1
ELSE DATA
END
FROM
(select top 10000 (ABS(CHECKSUM(NewId())) % 99 +1) * (ABS(CHECKSUM(NewId())) % 99 +1 ) DATA
from master..spt_values t1
cross JOIN master..spt_values t2) exponential
--Create temp work table and variables to calculate percentiles
Declare @hitsPerGroup as int
Declare @numGroups as int
Declare @dataPoints as int
set @numGroups=100
select @hitsPerGroup=SUM(HITS_SQRT)/(@numGroups -1)-@numGroups, @dataPoints=COUNT(*) FROM #Rank_Table
--show the number of hits that each group should have
select @hitsPerGroup HITS_PER_GROUP
--Use temp table for the calculation
CREATE TABLE #tbl (
row int,
hits int,
ID bigint,
PERCENTILE smallint null
)
--add index to row
CREATE CLUSTERED INDEX idxRow ON #tbl(row)
insert INTO #tbl
select ROW_NUMBER() over (ORDER BY HITS), hits_SQRT, ID, null from #Rank_Table
--Update each row with a running total.
--lower the percentile by one when we cross a threshold for the maximum number of hits per group (@hitsPerGroup)
DECLARE @row as int
DEClare @runningTotal as int
declare @percentile int
set @row = 0
set @runningTotal = 0
set @percentile = @numGroups
while @row <= @dataPoints
BEGIN
select @runningTotal=@runningTotal + hits from #tbl where row=@row
if @runningTotal >= @hitsPerGroup
BEGIN
update #tbl
set PERCENTILE=@percentile
WHERE PERCENTILE is null and row <@row
set @percentile = @percentile - 1
set @runningTotal = 0
END
--change rows
set @row = @row + 1
END
--get remaining
update #tbl
set PERCENTILE=@percentile
WHERE PERCENTILE is null
--update source data
UPDATE m SET PERCENTILE = t.PERCENTILE
FROM #tbl t
inner join #Rank_Table m on t.ID=m.ID
--Show the results
SELECT PERCENTILE, COUNT(id) NUMBER_RECORDS, SUM(HITS) HITS_IN_PERCENTILE
FROM #Rank_Table
GROUP BY PERCENTILE
ORDER BY PERCENTILE
--cleanup
DROP TABLE #Rank_Table
DROP TABLE #tbl
它的性能不是一流的,但它达到了平滑滑动分布的目的。