愚蠢的简单问题,我最终花了3.5个小时。我遇到了很多语法错误,所以如果有人能帮我解答这个问题,我会学到很多东西!非常感谢你!
我有3个数据库表:
Students Table
student_id, name
1, joe
2, jill
Courses Table
course_id, course_name
eng123, Engineering
stat111, Statistics
Marks Table
student_id, course_id, mark
1, stat111, 64
2, stat111, 90
1, eng123, 86
我需要编写一个SQL查询,它会给我一个总结的报告卡,如下所示:
student_id, student_name, eng123, stat 111
1, joe, 86, 64
2, jill, null, 90
---我探索的内容: 我已经把PIVOT,CASE和GROUP BY作为我的主要领导,但我不能把最后的作品放在一起。到目前为止,我最有希望的查询是:
SELECT Students.student_id, Students.student_name,
CASE course_id WHEN 'eng123' THEN mark END as 'eng123',
CASE course_id WHEN 'stat111' THEN mark END as 'stat111'
FROM Students
INNER JOIN Marks
ON Students.student_id=Marks.student_id;
但这给了我不正确的结果:
student_id, student_name, eng123, stat111
1, joe, null, 64
1, joe, 86, null
2, jill, null, 90
答案 0 :(得分:1)
您有希望的查询距离您想要的东西还有一箭之遥。您只需将其修改为GROUP BY
student_id
和student_name
(应始终将它们配对在一起)。然后取标记的总和。请注意,我在ELSE
语句中添加了CASE
条件,这些条件赋值为0(因此不会影响总和)。
SELECT Students.student_id, Students.student_name,
SUM(CASE course_id WHEN 'eng123' THEN mark ELSE 0 END) as 'eng123',
SUM(CASE course_id WHEN 'stat111' THEN mark ELSE 0 END) as 'stat111'
FROM Students
INNER JOIN Marks ON Students.student_id=Marks.student_id
GROUP BY Students.student_id, Students.student_name
答案 1 :(得分:0)
select student_id,student_name,
max(case when course_id = 'eng123' then mark end) as eng123,
max(case when course_id = 'stat111' then mark end) as stat111
from (
SELECT Students.student_id as student_id,
Students.name as student_name,
Marks.course_id as course_id,
Marks.mark as mark
FROM Student Students
INNER JOIN Marks
ON Students.student_id=Marks.student_id)Z
group by student_id,student_name
答案 2 :(得分:0)
您好尝试使用聚合函数MAX。试试这个:
WITH x AS (SELECT 1 AS student_id, 'joe' AS student_NAME FROM dual UNION ALL
SELECT 2 AS student_id, 'jill' AS student_NAME FROM dual),
y AS (SELECT 1 AS student_id , 'stat111' AS course_id, 64 AS mark FROM dual UNION ALL
SELECT 2 AS student_id , 'stat111' AS course_id, 90 AS mark FROM dual UNION ALL
SELECT 1 AS student_id , 'eng123' AS course_id, 86 AS mark FROM dual )
SELECT x.student_id, x.student_name,
MAX (CASE WHEN course_id = 'eng123' THEN mark END) eng123,
max(CASE WHEN course_id = 'stat111' THEN mark END) stat111
FROM x
INNER JOIN y
ON x.student_id=y.student_id
group by x.student_id, x.student_name;