0

我正在尝试计算可能与给定老师一起参加多个课程的学生对给定问题的总答案以及对给定问题的总正确答案。我想要按测试和老师分组的结果,并删除重复的学生。

我想从以下内容中得到的是:

test1-teacher1-6-4
test1-teacher2-3-2

但是,student3、student4 和 student5 与teacher1(见下文)在不同的班级注册这一事实导致它们被计算两次,所以我得到......

test1-teacher1-6-6
test1-teacher2-3-2

这是我正在使用的所有数据。

关于如何删除重复学生的任何想法?谢谢。

create database test_db;

use test_db;

drop table if exists test;
create table test(test_name varchar (50),student_name varchar(50),result varchar(50));


drop table if exists roster;
create table roster(teacher_name varchar(50),student_name varchar(50), class_name varchar(50));

insert into test values ('test1','student1','c');
insert into test values ('test1','student2','x');
insert into test values ('test1','student3','x');
insert into test values ('test1','student4','c');
insert into test values ('test1','student5','c');
insert into test values ('test1','student6','c');
insert into test values ('test1','student7','c');
insert into test values ('test1','student8','x');

insert into roster values ('teacher1', 'student1', 'class1'); 
insert into roster values ('teacher1', 'student2', 'class1'); 
insert into roster values ('teacher1', 'student3', 'class1');
insert into roster values ('teacher1', 'student4', 'class1');
insert into roster values ('teacher1', 'student5', 'class1');
insert into roster values ('teacher1', 'student6', 'class1');

insert into roster values ('teacher1', 'student3', 'class2');
insert into roster values ('teacher1', 'student4', 'class2');
insert into roster values ('teacher1', 'student5', 'class2');

insert into roster values ('teacher2', 'student6', 'class3');
insert into roster values ('teacher2', 'student7', 'class3');
insert into roster values ('teacher2', 'student8', 'class3');



use test_db;
select 
    test_name,
    r.teacher_name,
    count(distinct r.student_name) as numTested,
    sum(case
        when result = 'c' then 1
        else null
    end) as Q1correct
from
    test t
        join
    roster r ON t.student_name = r.student_name
group by t.test_name , r.teacher_name;
4

1 回答 1

1

使用子查询从roster.

select 
    test_name,
    r.teacher_name,
    count(distinct r.student_name) as numTested,
    sum(case
        when result = 'c' then 1
        else null
    end) as Q1correct
from
    test t
        join
    (select distinct teacher_name, student_name
     from roster) r ON t.student_name = r.student_name
group by t.test_name , r.teacher_name;

SQLFIDDLE

于 2013-10-24T01:34:36.527 回答