how to select, average and sort in mysql table

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

i have a table in mySql like in this picture

and i want to write a query which result will group by LESSON column, and add new row which is average value of LESSON column and sum CNT column values....
for this query i use this one

i use this query but it gives result like in picture 3 and i cant sort by PERC in this case

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 

回答1:

It looks like you're selecting all of the rows where lesson is CHEM, and then you want an extra row with the average of the percantage. How about:

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; 

Note that the sorting is performed by the outer query.



回答2:

don't know if you're looking for something like this:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!