将多个count语句组合到单个select语句中

时间:2011-02-14 05:32:42

标签: sql postgresql

我有一张表来跟踪学生在课程中参加考试的成功与失败情况如下。

      Column   |  Type   |                        Modifiers                        
------------+---------+---------------------------------------------------------
 id         | integer | not null default nextval('assessment_id_seq'::regclass)
 student_id | integer | not null
 lesson_id  | integer | not null
 correct    | boolean | default false

现在,我需要生成一份学生报告。报告只显示尝试次数总数,以及正确次数作为分数 - 每节课。

select count(*) as score from assessment where correct = true and student_id = 1 group by lesson_id 

select count(*) as total_attempts from assessment  where student_id = 1 group by lesson_id .

我想将这两个查询组合到一个查询中。我怎么能这样做..

感谢。

1 个答案:

答案 0 :(得分:3)

SELECT COUNT(*) as total_attempts,
  COUNT(CASE WHEN correct = true THEN 1 ELSE NULL END) as score
FROM assessment
WHERE student_id = 1
GROUP BY lesson_id