选择MAX并计算AVG

时间:2019-07-20 03:27:40

标签: mysql sql

如何从C2中选择MAX 5(最大值),然后根据MAX 5的选择获得C1的AVG值

+----+-------+
| C1 |   C2  |
+----+-------+
|  1 |   2.0 |
|  2 |   1.0 |
|  3 |   4.0 |
|  4 |   7.0 |
|  5 |   5.0 |
|  6 |   4.0 |
|  7 |   3.5 |
|  8 |   8.5 |
+----+-------+

2 个答案:

答案 0 :(得分:2)

您也可以通过以下方式做到这一点:

SELECT AVG(C1) 
FROM (
      SELECT c1, c2 
      FROM tbl 
      ORDER BY c2 DESC 
      LIMIT 5
      ) as tbl2

答案 1 :(得分:0)

您可以尝试使用最多5个c2和avg()的子查询

    select  avg(c1 )
    from my_table  m 
    inner join  (
        select  c2 
        from my_table  
        order by c2 desc 
        limit 5 
    ) t on m.c2 = t.c2