查找每组购买产品的前10%然后找到10%的平均值

时间:2016-11-19 00:38:01

标签: mysql sql

原谅我的英语。我不确定这在MySQL中是否可行。

我正在努力:

  1. 找出每个groupid得分的前10%
  2. 然后找到平均值 分数为10%by groupid
  3. 数据的示例子集:

    Table name: points
    
    groupid       score
    group_001     13
    group_001     12
    group_001     10
    group_001     12
    ...
    group_002     12
    group_002     16
    group_002     19
    group_002     20
    group_002     12
    group_002     13
    ...
    group_003     29
    group_003     21
    group_003     18
    ...
    

    ...

    这可能吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

你可以做到,但这有点棘手。 。 。变量是最简单的方法:

select group_id, avg(score)
from (select p.*,
             (@rn := if(@g = group_id, @rn + 1,
                        if(@g := group_id, 1, 1)
                       )
             ) as seqnum
      from points p cross join
           (select @rn := 0, @g := -1) params
      order by group_id, score desc
     ) p join
     (select group_id, count(*) as cnt
      from points
      group by group_id
     ) pp
     on pp.group_id = p.group_id
where (seqnum - 1) * 10 <= pp.cnt
group by group_id;