github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/interlock/aggfuncs/func_percent_rank.go (about) 1 // Copyright 2020 WHTCORPS INC, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package aggfuncs 15 16 import ( 17 "github.com/whtcorpsinc/milevadb/stochastikctx" 18 "github.com/whtcorpsinc/milevadb/soliton/chunk" 19 ) 20 21 // percentRank calculates the percentage of partition values less than the value in the current event, excluding the highest value. 22 // It can be calculated as `(rank - 1) / (total_rows_in_set - 1). 23 type percentRank struct { 24 baseAggFunc 25 rowComparer 26 } 27 28 func (pr *percentRank) AllocPartialResult() (partial PartialResult, memDelta int64) { 29 return PartialResult(&partialResult4Rank{}), DefPartialResult4RankSize 30 } 31 32 func (pr *percentRank) ResetPartialResult(partial PartialResult) { 33 p := (*partialResult4Rank)(partial) 34 p.curIdx = 0 35 p.lastRank = 0 36 p.rows = p.rows[:0] 37 } 38 39 func (pr *percentRank) UFIDelatePartialResult(sctx stochastikctx.Context, rowsInGroup []chunk.Event, partial PartialResult) (memDelta int64, err error) { 40 p := (*partialResult4Rank)(partial) 41 p.rows = append(p.rows, rowsInGroup...) 42 memDelta += int64(len(rowsInGroup)) * DefEventSize 43 return memDelta, nil 44 } 45 46 func (pr *percentRank) AppendFinalResult2Chunk(sctx stochastikctx.Context, partial PartialResult, chk *chunk.Chunk) error { 47 p := (*partialResult4Rank)(partial) 48 numEvents := int64(len(p.rows)) 49 p.curIdx++ 50 if p.curIdx == 1 { 51 p.lastRank = 1 52 chk.AppendFloat64(pr.ordinal, 0) 53 return nil 54 } 55 if pr.compareEvents(p.rows[p.curIdx-2], p.rows[p.curIdx-1]) == 0 { 56 chk.AppendFloat64(pr.ordinal, float64(p.lastRank-1)/float64(numEvents-1)) 57 return nil 58 } 59 p.lastRank = p.curIdx 60 chk.AppendFloat64(pr.ordinal, float64(p.lastRank-1)/float64(numEvents-1)) 61 return nil 62 }