所以,
我有3张桌子。用户(Id,FirstName,LastName)
课程(CourseId,CourseTitle,Faculty)
CourseEnrollment(StudentId,CourseId,FinalGrade)
现在,我应该:
用
创建视图
一个。学生名字
湾学生姓氏
C。课程名称
d。学院名字
即教师姓氏
F。最终成绩
由于学生和学院的名字都存储在一个表(用户)中,我决定制作学生名字,学生姓氏和课程名称的临时视图。
CREATE VIEW FirstView ([Student First Name],[Student Last Name],[Course Title])
AS
SELECT Users.FirstName,Users.LastName, Courses.CourseTitle
FROM Users
INNER JOIN CourseEnrollment
ON CourseEnrollment.StudentId=Users.NTID
INNER JOIN Courses
ON Courses.CourseId=CourseEnrollment.CourseId;
现在正在做主要工作......我正在创建一个像这样的新视图:
SELECT FirstView.[Student First Name],FirstView.[Student Last Name],FirstView.[Course Title], Users.FirstName, Users.LastName, CourseEnrollment.FinalGrade
FROM FirstView
JOIN Courses
ON Courses.CourseTitle LIKE FirstView.[Course Title] -- only those courses which are there in first view
JOIN Users
ON Users.NTID LIKE Courses.Faculty -- only the faculty users added
INNER JOIN CourseEnrollment
ON CourseEnrollment.CourseId LIKE Courses.CourseId;
问题是......如果我不添加最终成绩列和加入CourseEnrollment ......它可以正常工作。但是,一旦我这样做,它就会弄得一团糟,为每个学生制作多行。与其他学生的成绩。
任何人都知道如何解决这个问题?
答案 0 :(得分:1)
如果课程表中的faculty
字段引用用户,则可能是您想要的:
MS SQL Server 2012架构设置:
CREATE TABLE Users ( Id int , FirstName varchar(20), LastName varchar(20))
CREATE TABLE Courses ( CourseId int , CourseTitle varchar(20), Faculty int)
CREATE TABLE CourseEnrollment ( StudentId int, CourseId int, FinalGrade int)
INSERT Users VALUES (1, 'John', 'Adams')
INSERT Users VALUES (2, 'Steve', 'Student')
INSERT Users VALUES (3, 'Fred', 'Faculty')
INSERT Courses VALUES (1, 'DB 101', 3)
INSERT Courses VALUES (2, 'DB 201', 3)
INSERT CourseEnrollment VALUES (1,1,30)
INSERT CourseEnrollment VALUES (2,1,50)
INSERT CourseEnrollment VALUES (2,2,75)
查询1 :
SELECT
u.FirstName AS [Student FirstName], u.LastName as [Student LastName],
c.CourseTitle,
faculty.FirstName AS [Faculty FirstName],
faculty.LastName AS [Faculty LastName],
ce.FinalGrade
FROM Users u
INNER JOIN CourseEnrollment ce ON u.Id = ce.StudentId
INNER JOIN Courses c ON c.CourseId = ce.CourseId
INNER JOIN Users faculty ON c.Faculty = faculty.Id
<强> Results 强>:
| STUDENT FIRSTNAME | STUDENT LASTNAME | COURSETITLE | FACULTY FIRSTNAME | FACULTY LASTNAME | FINALGRADE |
|-------------------|------------------|-------------|-------------------|------------------|------------|
| John | Adams | DB 101 | Fred | Faculty | 30 |
| Steve | Student | DB 101 | Fred | Faculty | 50 |
| Steve | Student | DB 201 | Fred | Faculty | 75 |