我可能会混淆其他语言的SQL语法,这就是为什么它不起作用,我的子查询肯定是不正确的。
有以下2个表:
TEST_RESULTS
Student_ID Test_ID Test_Result
A1 234 90
B2 234 80
C3 345 85
D4 234 95
A1 345 95
C3 456 95
TEST_DESCRIPTION
Test_ID Test_Description Passing_Score
234 Test A 85
345 Test B 90
456 Test C 95
我想计算每次测试的传递率并按它排序。
我正在寻找的输出:
Test_ID Test_Description students_taking students_passing rate
456 Test C 1 1 1
234 Test A 3 2 0.666666667
345 Test B 2 1 0.5
这是我的查询
SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_taking, students_passing, students_passing/students_taking as rate
FROM
(SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_passing
FROM TEST_RESULTS tr
JOIN TEST_DESCRIPTION td
on tr.Test_ID = td.Test_ID
WHERE tr.Test_Result > td.)
GROUP BY td.Test_ID, td.Test_Description
ORDER BY rate DESC, td.Test_ID, td.Test_Description
我从select中选择是错误的,因为我的查询没有结果。
答案 0 :(得分:2)
我正在使用CTE,LEFT JOIN来获得所需的结果。 试试这个查询 -
;WITH CTE
AS
(
SELECT
TD.TEST_ID,
TEST_DESCRIPTION,
COUNT(TR.STUDENT_ID) AS STUDENTS_TAKING,
COUNT(CASE WHEN TR.TEST_RESULT >= TD.PASSING_SCORES THEN
TR.STUDENT_ID END) AS STUDENTS_PASSING
FROM TEST_DESCRIPTION TD
LEFT JOIN TEST_RESULTS TR
ON TD.TEST_ID = TR.TEST_ID
GROUP BY TD.TEST_ID,
TEST_DESCRIPTION
)
SELECT
TEST_ID,
TEST_DESCRIPTION,
STUDENTS_TAKING,
STUDENTS_PASSING,
STUDENTS_PASSING / CONVERT (DECIMAL(4,2),STUDENTS_TAKING) AS RATE
FROM CTE
ORDER BY TEST_DESCRIPTION
答案 1 :(得分:1)
SELECT td.Test_ID, td.Test_Description,
students_taking = counts.students_taking,
students_passing = counts.students_passing,
rate = counts.rate
FROM TEST_DESCRIPTION td
OUTER APPLY (
SELECT
students_taking = COUNT(1),
students_passing = COUNT(CASE WHEN tr.Test_Result > td.Passing_score THEN 1 ELSE NULL END),
rate = IIF(COUNT(1) <> 0, COUNT(CASE WHEN tr.Test_Result > td.Passing_score THEN 1 ELSE NULL END) / CAST(COUNT(1) AS FLOAT), 0)
FROM TEST_RESULTS tr
WHERE tr.Test_ID = td.Test_ID
) counts
ORDER BY counts.rate DESC, td.Test_ID
答案 2 :(得分:1)
请查看以下查询 -
SELECT TD.TEST_ID,
TD.TEST_DESCRIPTION,
STUDENT_TAKING,
STUDENT_PASSING,
RATE
FROM TEST_DESCRIPTION TD,
(SELECT TR.TEST_ID,COUNT(TR.STUDENT_ID) "STUDENT_TAKING",
COUNT(CASE WHEN TEST_RESULT>=PASSING_SCORE THEN STUDENT_ID END) STUDENT_PASSING,
TO_NUMBER(TO_CHAR(COUNT(CASE WHEN TEST_RESULT>=PASSING_SCORE THEN STUDENT_ID END)/COUNT(TR.STUDENT_ID),'9999.99')) RATE
FROM TEST_RESULTS TR,TEST_DESCRIPTION TD
WHERE TR.TEST_ID=TD.TEST_ID
GROUP BY TR.TEST_ID)SUB
WHERE SUB.TEST_ID=TD.TEST_ID ORDER BY RATE DESC;