1.在SQL SERVER“吕海洋学生管理”数据库中,按如下要求设计和建立视图: (1)基于单个表按投影操作定义视图。 (2)基于单个表按选择操作定义视图。 (3)基于2个表根据连接操作定义视图。 (4)基于2个表根据嵌套操作定义视图。 (5)定义含有虚字段的视图。
时间: 2024-10-17 20:09:08 浏览: 43
在 SQL Server 中,设计和建立视图可以帮助简化查询并隐藏底层数据细节。以下是按照你提供的要求分别创建视图的示例:
1. **按投影操作定义视图(Select only specific columns)**:
```sql
CREATE VIEW vw_StudentInfo AS
SELECT StudentID, Name, Age
FROM Students;
```
这个视图仅包含学生的学号、姓名和年龄。
2. **按选择操作定义视图(Include additional conditions)**:
```sql
CREATE VIEW vw_AdvancedSearch AS
SELECT * FROM Students
WHERE Gender = 'Male';
```
这个视图显示所有男性学生的信息。
3. **基于两个表的连接操作定义视图(Joining tables)**:
假设我们有 Students 和 Courses 表,可以这样创建:
```sql
CREATE VIEW vw_CoursesTaken AS
SELECT Students.Name, Courses.CourseName
FROM Students
INNER JOIN Enrollments ON Students.StudentID = Enrollments.StudentID
INNER JOIN Courses ON Enrollments.CourseID = Courses.CourseID;
```
此视图展示了每个学生所选课程的名称。
4. **基于两个表的嵌套操作定义视图(Subqueries in the view definition)**:
```sql
CREATE VIEW vw_TopPerformers AS
SELECT s.Name, c.CourseName
FROM Students s
JOIN (
SELECT CourseID, AVG(Score) as AvgScore
FROM Grades
GROUP BY CourseID
) g ON s.StudentID IN (
SELECT StudentID
FROM Grades
WHERE Score > (SELECT AVG(Score) FROM Grades)
)
JOIN Courses c ON g.CourseID = c.CourseID;
```
这个视图展示平均成绩超过全班平均水平的学生及其所选课程。
5. **定义含有虚字段的视图(Computed fields)**:
```sql
CREATE VIEW vw_StudentAwards AS
SELECT StudentID, Name, AwardName = CASE WHEN TotalPoints >= 80 THEN 'Outstanding' ELSE 'Excellent' END AS GradeLevel
FROM (
SELECT Students.*, SUM(Questions.Points) AS TotalPoints
FROM Students
JOIN Questions ON Students.StudentID = Questions.StudentID
GROUP BY Students.StudentID
) student_points;
```
这个视图根据总分将学生分为优秀和杰出两类。
阅读全文