2011-02-14 102 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