Reputation:
Query 1
select test_id, count (student_id)*100/
(select count(distinct student_id)from test_taken)as "pass rate"
from test_taken
where result>50
group by test_id;
Query 2
select test_id, count (student_id)*100/
(select count(distinct student_id)from test_taken)as "fail rate"
from test_taken
where result<50
group by test_id;
I have the following Table:
test_taken
Columns:test_id,student_id,result
I am looking to get the percentage pass rate and fail rate where a pass is result >50% and fail is result <50%.
I have the pass rate and fail rate as 2 separate queries but I want them combined into one query.
Upvotes: 1
Views: 83
Reputation: 1583
The OPs solution does not produce a correct result (at least not the one specified in the requirements) so expanding on that with UNION or other methods is NOT a valid answer. He seems to be calculating the percentages on the entire number of students instead of just the ones that took a specific test.
A query which would produce the correct result for each test is the following:
select Q1.test_id,
Q1.students_passed * 100 / Q1.total_students || '%' as pass_rate,
Q1.students_failed * 100 / Q1.total_students || '%' as fail_rate
from
(SELECT test_id,
sum(case when result > 50 then 1 else 0 end) students_passed,
sum(case when result < 50 then 1 else 0 end) students_failed,
count(distinct student_id) total_students
FROM test_taken
GROUP BY test_id) Q1;
We first count how many students have passed and failed using the SUM function. We add one to the sum when our coditions are met, i.e result > 50 or result < 50, else we add zero.
We also need to count the total nr. of students that have taken a test, so we can do that easily with count(distinct student_id) and grouping by test_id.
Finally we wrap this query in the outer one, in which we divide the the nr. of students passed and failed to the total nr of students for each a given test_id.
For the input table:
1 | 1 | 51 1 | 2 | 30 2 | 3 | 60 2 | 4 | 22 3 | 2 | 66
it produces the output:
1 | 50% | 50% 2 | 50% | 50% 3 | 100% | 0%
Upvotes: 0
Reputation: 204746
SELECT test_id,
sum(case when result > 50 then 1 else 0 end) * 100 / (SELECT COUNT(DISTINCT student_id)
FROM test_taken) AS "pass rate",
sum(case when result < 50 then 1 else 0 end) * 100 / (SELECT COUNT(DISTINCT student_id)
FROM test_taken) AS "fail rate"
FROM test_taken
GROUP BY test_id;
Upvotes: 1
Reputation: 3755
If the result of the two queries is equal in terms of column numbers and column types, you can use UNION
to get one table result :
SELECT test_id,
COUNT (student_id) * 100 / (SELECT COUNT(DISTINCT student_id)
FROM test_taken)AS rate
FROM test_taken
WHERE result > 50
GROUP BY test_id;
UNION
SELECT test_id,
COUNT (student_id) * 100 / (SELECT COUNT(DISTINCT student_id)
FROM test_taken)AS rate
FROM test_taken
WHERE result < 50
GROUP BY test_id;
Upvotes: 0