-1

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

在此处输入图像描述

4

2 回答 2

0

看起来您正在选择lessonis的所有行CHEM,然后您想要一个具有平均百分比的额外行。怎么样:

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-04-12T13:02:07.600 回答
-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;
于 2012-04-12T12:03:12.253 回答