[英]Retrieve Data from Different Tables (SQL Server)
I have 4 tables in a SQL Server database with following schema: 我在具有以下架构的SQL Server数据库中有4个表:
Attendance 勤
CREATE TABLE [dbo].[Attendance] ( [AttendanceId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL, [CourseId] UNIQUEIDENTIFIER NOT NULL, [StudentId] UNIQUEIDENTIFIER NOT NULL, [SubjectId] UNIQUEIDENTIFIER NOT NULL, [Semester] INT NOT NULL, [Month] NVARCHAR (50) NOT NULL, [Count] INT NOT NULL, CONSTRAINT [PK_Attendance] PRIMARY KEY NONCLUSTERED ([AttendanceId] ASC), CONSTRAINT [FK_Attendance_Student] FOREIGN KEY ([StudentId]) REFERENCES [dbo].[Student] ([StudentId]) );
Course 课程
CREATE TABLE [dbo].[Course] ( [CourseId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL, [Name] NVARCHAR (50) NOT NULL, CONSTRAINT [PK_Course] PRIMARY KEY NONCLUSTERED ([CourseId] ASC) );
Student 学生
CREATE TABLE [dbo].[Student] ( [StudentId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL, [CourseId] UNIQUEIDENTIFIER NOT NULL, [Name] NVARCHAR (100) NOT NULL, [RollNo] INT NOT NULL, [Semester] INT NOT NULL, CONSTRAINT [PK_Student] PRIMARY KEY NONCLUSTERED ([StudentId] ASC), CONSTRAINT [FK_Student_Course] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId]) );
Subject 学科
CREATE TABLE [dbo].[Subject] ( [SubjectId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL, [CourseId] UNIQUEIDENTIFIER NOT NULL, [Name] NVARCHAR (100) NOT NULL, [Semester] INT NOT NULL, CONSTRAINT [PK_Subject] PRIMARY KEY NONCLUSTERED ([SubjectId] ASC), CONSTRAINT [FK_Subject_Course] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId]) );
I need to create a attendance report in the following format: 我需要以以下格式创建出勤报告:
Course Name | 课程名称 | Student Name | 学生姓名 | Subject Name | 主题名称 | Semester | 学期 | Month | 月 | Count 计数
Please tell me what SQL Query I need to use and if there's any change in schema required then suggest the same. 请告诉我我需要使用什么SQL查询,如果架构需要任何更改,请提出相同的建议。
I'm looking forward to have your replies. 希望收到您的答复。
Thanks, 谢谢,
You need to use a JOIN
in your query so that it only returns rows which match a [StudentId]
from the Attendance table. 您需要在查询中使用JOIN
,以便它仅返回与Attendance表中的[StudentId]
匹配的行。
eg 例如
SELECT c.CourseName, s.StudentName, u.SubjectName, u.Semester, a.Month, a.Count
FROM Student s
JOIN Attendance a ON s.StudentId = a.StudentId
JOIN Course c ON a.CourseId = c.CourseId
JOIN Subject u ON c.CourseId = u.CourseId
Something along these lines will only return rows which specifically match 这些行中的内容只会返回专门匹配的行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.