SQL使用联接从多个表中选择记录

时间:2019-02-11 13:55:43

标签: sql join

我想要以下情况的SQL选择查询。我有6张桌子。

1)大学

  • Univ_id
  • 大学名称

2)大学

  • College_id
  • 学院名称
  • Univ_id(FK)

3)部门

  • Dept_id
  • 部门名称
  • College_id(FK)

4)主题

  • Subject_id
  • 主题名称

5)学生

  • Student_id
  • 学生姓名
  • Dept_id(FK)
  • Subject_id(FK)

6)Student_Subject

  • Student_id(FK)
  • Subject_id(FK)
  • 标记

我想要每个科目和每个大学的分数总和。请建议和SQL语句相同。

2 个答案:

答案 0 :(得分:0)

每个科目的分数:

SELECT su.subject_Name,
       sum(ss.marks)
FROM student_subject ss
JOIN subjects su ON ss.subject_id = su.subject_id
GROUP BY su.subject_Name

每所大学的分数:

SELECT u.university_name,
       sum(ss.marks)
FROM student_subject ss
JOIN student st ON st.student_id = ss.student_id
JOIN department d ON d.dept_id = st.dept_id
JOIN college c ON c.college_id = d.college_id
JOIN university u ON u.univ_id = c.univ_id
GROUP BY u.university_name

答案 1 :(得分:0)

这应该有效:

SELECT u.university_name, su.subject_name, sum(ss.marks) sum_of_marks
FROM university u
JOIN college c ON c.univ_id=u.univ_id
JOIN department d ON d.college_id=c.college_id
JOIN student st ON st.dept_id = d.dept_id
JOIN student_subject ss ON ss.student_id=st.student_id
JOIN subjects su ON su.subject_id=ss.subject_id
GROUP BY  u.university_name, su.subject_name