2011-02-14 101 views
2

我有表格来跟踪成功,失败的学生在一门课程中参加如下考试。将多个计数语句合并为单个选择语句

 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 . 

我想将这两个查询结合到一个查询中。我该如何做到这一点..

谢谢。

回答

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