如何在mysql表中选择,平均和排序

时间:2012-04-12 11:58:31

标签: mysql select average

我在mySql中有一张表,如图所示 enter image description here

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

enter image description here

我使用这个查询但它给出的结果如图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

enter image description here

2 个答案:

答案 0 :(得分:0)

看起来您正在选择lessonCHEM的所有行,然后您需要一个额外的行,其中包含percantage的平均值。怎么样:

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;

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

答案 1 :(得分:-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;