0

我正在尝试构建一个 SQL 联合查询,该查询将返回两列(每个选择一个),其结果来自同一字段,并使用 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

有谁知道我应该怎么做?

4

2 回答 2

1

If the grades are supposed to be linked to the same student, I'm going to guess something like this:

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
于 2012-12-04T00:29:07.487 回答
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;
于 2012-12-04T00:21:30.757 回答