Question

I Have A table that shows each course a student is regisered in.

 StudID   Course   %         Symbol    GPA      Cond1    Cond2
|  1004 | STA2   | 55      | 3      |      24 | Y      | Y       |
|  1004 | Psy1   | 67      | 2-     |      24 | n      | Y       |
|  1005 | CS3    | 67      | 2-     |      36 | Y      | Y       |
|  1005 | ECO3   | 70      | 2+     |      18 | Y      | N       |
|  1005 | GAM1   | 77      | 1      |      24 | Y      | Y       |
|  1005 | GAM2   | 55      | 3      |      36 | Y      | Y       |
|  1005 | MAM3   | 52      | 3      |      36 | Y      | Y       |

How will I select the number of courses that a student doing PSY1 also does that fufills BOTH Cond1 and Cond 2? i.e 1004 does 1 course that passes both criteria and also does psy1

SELECT COUNT(*) FROM tblGrades WHERE Course = 'PSY' GROUP BY StudID;

Doesnt work. Thank you

ED: I need a list of all students doing PSY1, Along with teh ammount of OTHER courses they do which fufill bot cond1 and cond2.

Was it helpful?

Solution

E.g.:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(student_id INT NOT NULL
,course_code VARCHAR(12) NOT NULL
,pct INT NOT NULL
,symbol CHAR(3) NOT NULL
,GPA INT NOT NULL
,Condition_1 CHAR(1) NOT NULL
,Condition_2 CHAR(1) NOT NULL
,PRIMARY KEY(student_id,course_code)
);

INSERT INTO my_table VALUES
(1004  ,'STA2',  55,     '3'       ,24 ,'Y'  ,'Y'),
(1004  ,'Psy1',  67,     '2-'       ,24 ,'n'  ,'Y'),
(1005  ,'CS3',   67,     '2-'       ,36 ,'Y'  ,'Y'),
(1005  ,'ECO3',  70,     '2+'       ,18 ,'Y'  ,'N'),
(1005  ,'GAM1',  77,     '1'       ,24 ,'Y'  ,'Y'),
(1005  ,'GAM2',  55,     '3'       ,36 ,'Y'  ,'Y'),
(1005  ,'MAM3',  52,     '3'       ,36 ,'Y'  ,'Y');


SELECT x.student_id
     , COUNT(*) other_courses_total
  FROM my_table x 
  JOIN my_table y 
    ON y.course_code <> x.course_code 
   AND y.student_id = x.student_id 
 WHERE y.course_code = 'Psy1' 
   AND x.condition_1 = 'Y' 
   AND x.condition_2 = 'Y' 
 GROUP 
    BY x.student_id;

+------------+---------------------+ 
| student_id | other_courses_total |
+------------+---------------------+
|       1004 |                   1 |
+------------+---------------------+

If you want to include students with a score of zero, change the [INNER] JOIN to a LEFT JOIN and COUNT (or COALESCE(COUNT)) something on the right.

OTHER TIPS

Untested, but should give you a starter:

select t.studid, count(1)
from T
join (
    select distinct studid
    from T where Course = 'PSY'
) U
    on t.studid = u.studid 
where t.cond1 = 'Y' and t.cond2 = 'Y'
group by  t.studid
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top