如何从这个表中选择并添加平均值然后排序

时间:2012-04-12 13:05:28

标签: mysql select average

  

可能重复:
  how to select, average and sort in mysql table

我在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

1 个答案:

答案 0 :(得分:0)

select * from <your query> order by PERC

wich:

select * from (

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

) as sub order by PERC DESC