how to select, average and sort in mysql table

后端 未结 2 1539
Happy的楠姐
Happy的楠姐 2021-01-29 11:10

i have a table in mySql like in this picture
\"enter

and i want to write a query which

2条回答
  •  广开言路
    2021-01-29 11:41

    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 
      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 
      where lesson = "CHEM"
    ) q
    order by `perc` desc;
    

    Note that the sorting is performed by the outer query.

提交回复
热议问题