如何根据SQL中提交的结果聚合两个结果?

时间:2015-10-08 23:14:18

标签: sql

假设我有attemps.cvs,其格式为

(problem_id, people_id, answer);

people.cvs,其格式为

(people_id, last_name, first_name);

prolems.cvs,其格式为

(problem_id, answer)

在我创建三个表格并将数据填入其中之后,我想找到一个人有多少问题得到解答,并且回答正确?

  • 有多少问题得到解答?

    (加入尝试

    SELECT first_name,last_name,count(people.people_id)FROM people, 尝试WHERE people.people_id = attempts.people_id GROUP BY first_name,last_name,people.people_id);

  • 有多少问题得到了正确回答?

    (加入这三个)将 problems.answer = attempts.answer 添加到SQL的{​​{1}}条款。

问题:如何在一个WHERE内获得这两个信息?

3 个答案:

答案 0 :(得分:0)

实际上,如果您想知道有多少问题有一个答案,您不需要加入“人员”表。以下查询给出了只有一个答案的所有问题。

SELECT problems.problem_id
FROM attempts, problems
WHERE attempts.problem_id = problems.problem_id
and attemps.answer = problems.answer
and problem_id IN 
(
    SELECT problem_id
    FROM attempts
    GROUP BY problem_id
    HAVING count(*) = 1
);

要解决有一个答案并正确回答的问题:

add

答案 1 :(得分:0)

此查询打印一个答案的问题数量和正确回答的问题数量:

SELECT * FROM
(SELECT count(problem_id) as OneAnswer
FROM attempts
GROUP BY problem_id
HAVING count(*) = 1) as OA,
(SELECT count(problem_id) as AnsweredCorrectly
FROM problems
WHERE EXISTS(SELECT problem_id FROM attempts 
             WHERE attempts.problem_id = problems.problem_id 
             and attemps.answer = problems.answer)) as AC;

答案 2 :(得分:0)

此答案应打印人们回答每个问题的次数以及他们获得正确答案的次数。

注意:早些时候发生了轻微错误 - 抱歉。

SELECT b.people_id,
       COUNT(b.answer),
       c.CountCorrect
FROM attempts b,
     (SELECT a.people_id,
             COUNT( a.people_id )
      FROM attempts a,
           problems pr
      WHERE a.problem_id = pr.problem_id AND
            a.answer = pr.answer
      GROUP BY a.people_id) c
WHERE b.people_id = c.people_id
GROUP BY b.people_id;

此答案应打印人们已回答问题的次数以及他们获得正确答案的次数。

SELECT b.people_id,
       COUNT(b.answer),
       c.CountCorrect
FROM attempts b,
     (SELECT a.people_id,
             COUNT( a.people_id )
      FROM attempts a,
           problems pr
      WHERE a.answer = pr.answer
      GROUP BY a.people_id) c
WHERE b.people_id = c.people_id
GROUP BY b.people_id;
相关问题