共計 1347 個字符,預計需要花費 4 分鐘才能閱讀完成。
這篇文章主要為大家展示了“MySQL 百分位數如何計算”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓丸趣 TV 小編帶領大家一起研究并學習一下“MySQL 百分位數如何計算”這篇文章吧。
select query_time,d,max(ts) ts from (
select t2.query_time,ts,rn,round(rn/total,10) percent,
case
when 0.71 =round(rn/total,10) then 0.71
when 0.81 =round(rn/total,10) then 0.81
when 0.91 =round(rn/total,10) then 0.91
end d
from (
select query_time,ts,
case when @gid=query_time then @rn:=@rn+1 when @gid:=query_time then @rn:=1 end rn
from (
select * from t ,(select @gid:= ,@rn:=0) vars order by query_time,ts
) t1
) t2 inner join (
select query_time,count(*) total from t group by query_time
) t3 on(t2.query_time=t3.query_time)
where round(rn/total,10) =0.71
) t6
where d is not null
group by query_time,d
where round(rn/total,10) =0.71
即 用定義的最小的百分位數進行過濾后, 再 group by
此時 查詢時間可以低至 20.531 s
當然,這個 SQL 還有進一步提升的空間
計算 某個百分位數的位置, 有如下的公式:
loc=1+(n-1)*p,n 是元素數,p 是分位點。loc 大小介于 1 和 n 之間
那么 SQL 可以進行如下優化
select t5.query_time,t5.ts,t2.v from (
select query_time,total,v, floor(1+(total-1)*v) rn
from (
select query_time,count(*) total from t group by query_time
) t3, (select 0.71 v,1 seq union all select 0.81,2 union all select 0.91,3) t4
)
t2 inner join (
select
query_time,
case when @gid=query_time then @rn:=@rn+1 when @gid:=query_time then @rn:=1 end rn,
ts
from (
select * from t ,(select @gid:= ,@rn:=0) vars order by query_time,ts
) t1
) t5 on (t2.query_time=t5.query_time and t2.rn=t5.rn)
除了本身簡化了 SQL 復雜度, 查詢時間也低至 15 秒左右
以上是“MySQL 百分位數如何計算”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注丸趣 TV 行業資訊頻道!