【问题标题】:how to select, average and sort in mysql table如何在mysql表中选择,平均和排序
【发布时间】:2012-04-24 18:31:09
【问题描述】:

我在 mySql 中有一张像这张图片一样的表

我想编写一个查询,其结果将按 LESSON 列分组,并添加新行,即 LESSON 列的平均值和 CNT 列值的总和....
对于这个查询,我使用这个

我使用此查询,但它给出的结果如图 3 所示,在这种情况下我无法按 PERC 排序

select no, STUD_ID,CLASS,LESSON, AVG(PERC) as PERC,SUM(CNT) as CNT from t_lesson where LESSON='CHEM' group by CLASS
union all
select no,STUD_ID,CLASS,'AVERAGE' as LESSON, AVG(PERC) as PERC, SUM(CNT) as CNT from t_lesson where LESSON='CHEM' group by LESSON

【问题讨论】:

  • 你对哪些字段进行分组?
  • @namco 你的要求太复杂了,没有很好的解释,请正确解释。
  • 用我最糟糕的英语,这就是为什么我试图用图片来做:)
  • @namco 没问题,但试着多解释一下你想要的结果,因为我不明白为什么你的结果在一个 manar 中有四行,CHEM 的平均值显示在其他行之间CHEM.

标签: mysql select average


【解决方案1】:

不知道你是否在寻找这样的东西:

SELECT fields_list, (field_to_modify + (SELECT AVG(average_field) FROM table2)) AS order_field 
  FROM table1
WHERE your_conditions
  ORDER BY order_field;

【讨论】:

    【解决方案2】:

    您似乎选择了lessonCHEM 的所有行,然后您想要一个具有平均百分比率的额外行。怎么样:

    select *
    from (
      -- this part gets all the "CHEM" rows
      select * 
      from <your_table_name>
      where lesson = "CHEM"
      union
      -- this parts selects the aggregate row
      select 
        NULL            as `no`, 
        NULL            as `stud_id`, 
        NULL            as `class`,
        "average"       as `lesson`,
        avg(percentage) as `perc`, 
        sum(count)      as `cnt`
      from <your_table_name>
      where lesson = "CHEM"
    ) q
    order by `perc` desc;
    

    请注意,排序是由外部查询执行的。

    【讨论】:

      猜你喜欢
      • 2012-06-28
      • 2010-12-23
      • 2012-04-24
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2016-09-04
      • 2020-11-30
      • 2015-10-08
      相关资源
      最近更新 更多