How to calculate the average grade for each student

I have a table "Register"

with columns:

  class_id bigint NOT NULL,
  disciple text,
  datelesson date NOT NULL,
  student_id integer NOT NULL,
  note character varying(2)

now I want to calculate the average score for each student_id and the number of absent

Select * from "Register" as m

Join

(SELECT AVG(average), COUNT(abs) FROM (SELECT
  CASE
      WHEN "note" ~ '[0-9]' THEN CAST("note" AS decimal) 
  END AS average,
  CASE
      WHEN "note" ='a' THEN "note"
  END AS abs
FROM "Register" ) AS average)n 
on class_id=0001 
And datelesson between '01.01.2012' And  '06.06.2012' 
And discipline='music' order by student_id

Result:

0001;"music";"2012-05-02";101;"6";7.6666666666666667;1
0001;"music";"2012-05-03";101;"a";7.6666666666666667;1
0001;"music";"2012-05-01";101;"10";7.6666666666666667;1
0001;"music";"2012-05-02";102;"7";7.6666666666666667;1
0001;"music";"2012-05-03";102;"";7.6666666666666667;1
0001;"music";"2012-05-01";102;"";7.6666666666666667;1

The result I get applies to the entire column, but how can I calculate the average grades for each student?

+3
source share
2 answers

It might look like this:

SELECT student_id
     , AVG(CASE WHEN note ~ '^[0-9]*$' THEN note::numeric
                                       ELSE NULL END) AS average
     , COUNT(CASE WHEN note = 'a' THEN 1 ELSE NULL END) AS absent
FROM   "Register"
WHERE  class_id = 1 
AND    datelesson BETWEEN '2012-01-01' AND  '2012-06-06' 
AND    discipline = 'music'
GROUP  BY student_id
ORDER  BY student_id;

I have added some improvements.

  • You do not need to specify lowercase identifiers twice.
  • If you want to make sure that notethere are only numbers in your regular expression should be something like note ~ '^[0-9]*$'. What you have only checks if there is any digit in the line.
  • ISO , : YYYY-MM-DD.
  • count , NULL . Ypu sum.
  • class_id , bigint, , - .
    class_id = 1 class_id = 0001.
+3

, "group by". postgress, , .

transact-sql:

--create table  register
--(
--class_id bigint NOT NULL,
--  disciple text,
--  datelesson date NOT NULL,
--  student_id integer NOT NULL,
--  grade_report integer not null,
--  )


--drop table register

delete from register
go

insert into register 
    values( 1, 'math', '1/1/2011', 1, 1)
insert into register 
    values( 1, 'reading', '1/1/2011', 1, 2)
insert into register 
    values( 1, 'writing', '1/1/2011', 1, 5)

insert into register 
    values( 1, 'math', '1/1/2011', 2, 8)
insert into register 
    values( 1, 'reading', '1/1/2011', 2, 9)

SELECT student_id, AVG(grade_report) as 'Average',  COUNT(*) as 'NumClasses'
from register
WHERE  class_id=1
group by student_id
order by student_id

+2

All Articles