回答

收藏

获得最高和最低的第25个百分位数平均值

技术问答 技术问答 626 人阅读 | 0 人回复 | 2023-09-14

我有一张表,上面有员工名单以及他们出售的单位数量。
3 R5 f/ G. _6 V1 P我想获得售出的前25%的平均单位和售出的下25%的平均单位。
& x$ k! t# l/ ?8 h- r6 W我创建了我的数据SLQ小提琴的表示形式# L- K) X) T( [% h' S6 f
我真的不知道该如何开始?我看到的所有示例都是针对SQL Server而非MySQL。这就是我的想法。
, l. B& @! |3 T5 m7 j我想要25个百分点,不能限制为25个项目。基本上它将涉及:
7 F" U; _, [9 [* f* D1) #_of_employees = The number of total employees.# x. }3 P% q, m
2) #_of_employees_in_25_percentile =  #_of_employees*0.25, l4 h1 W8 d+ s7 [- [4 H7 o9 z
3) Calculate the sum of the units sold by the top/bottom 25 percentile (limit #_of_employees_in_25_percentile)( X3 Q# i9 p5 M. _
4) Divide the sum by #_of_employees_in_25_percentile to get the average.# b) Z0 D5 F- H
如何在MySQL中有效地完成所有这些工作?6 C( s" u7 `; `4 X9 @4 a  i$ w0 n  Q
               
2 Z4 v, w6 [0 O$ o5 A* i( r解决方案:, F4 ^) o0 F" |# G' v
               
$ P* L" a6 V3 M, i0 [* E
5 @" c6 s8 M+ }  H& t7 j% ]6 a* C
, h/ N8 t0 T8 G8 `  G                这是一个解决方案,它使用了我从这个问题中学到的一个诡计。8 ?3 B& k6 ~+ [: |& {5 m
SELECT id, unit_sold, n * 100 / @total AS percentile; ?7 d9 c, U" x  @
FROM (& C  j) j3 C4 z$ C* V( J5 `6 Y
  SELECT id, unit_sold, @total := @total + unit_sold AS n
. k0 @1 O  o- {/ l  P  FROM mydata, (SELECT @total := 0) AS total
, D- [7 T8 c3 d' i; L, O8 |  ORDER BY unit_sold ASC# I. c- W+ X0 O
) AS t
5 u# Q' d0 w' C; A+ O, o6 hSQL提琴。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则