我正在尝试构建一个SQL Union Query,它将返回两列(每个select一个),其中包含来自同一字段的结果,并使用WHERE子句进行排序。
以下是我的尝试:
SELECT scg.grade AS course_1
FROM cp_StudentCourseGrade AS scg
JOIN cp_CourseSecSem AS css ON
css.courseSecSem_id = scg.courseSecSem_id
JOIN cp_Course AS c1 ON
c1.course_id = css.course_id
UNION
SELECT scg.grade AS course_2
FROM cp_StudentCourseGrade AS scg
JOIN cp_CourseSecSem AS css ON
css.courseSecSem_id = scg.courseSecSem_id
JOIN cp_Course AS c2 ON
c2.course_id = css.course_id**
WHERE c1.course_id = c2.course_id AND c1.course_id=1 AND c2.course_id=2;
这应该给我这样的东西:
course_1 | course_2
-------------------
4.0 | 6.0
4.5 | 6.0
6.0 | 5.5
2.5 | 5.0
1.0 | 4.0
5.5 | 4.5
但我收到的错误是:
未知栏c1.course_id
有没有人知道我应该怎么做?
答案 0 :(得分:1)
这就是你需要的:
SELECT scg1.grade AS course_1, scg2.grade AS course_2
FROM cp_StudentCourseGrade AS scg1
JOIN cp_CourseSecSem AS css1 ON
css1.courseSecSem_id = scg1.courseSecSem_id
JOIN cp_Course AS c1 ON
c1.course_id = css1.course_id AND c1.course_id=1
JOIN cp_StudentCourseGrade AS scg2
JOIN cp_CourseSecSem AS css2 ON
css2.courseSecSem_id = scg2.courseSecSem_id
JOIN cp_Course AS c2 ON
c2.course_id = css2.course_id AND c2.course_id=2;
答案 1 :(得分:1)
如果成绩应该与同一个学生相关联,我会猜到这样的事情:
Select
scg.student_id,
Sum(Case When css.course_id = 1 Then scg.grade Else Null End) as course_1,
Sum(Case When css.course_id = 2 Then scg.grade Else Null End) as course_2
From
cp_StudentCourseGrade As scg
Inner Join
cp_CourseSecSem As css
On css.courseSecSem_id = scg.courseSecSem_id
Group By
scg.student_id