sql server写查询各科成绩均大于平均成绩的学生学号,姓名
时间: 2025-01-01 19:40:30 浏览: 6
你可以使用SQL Server的`AVG()`函数计算每个科目的平均成绩,然后通过`WHERE`子句筛选出成绩大于平均分的学生。假设有一个名为`StudentScores`的表,包含字段`StudentID`, `Name`, 和 `ScoreBySubject`(科目分数),查询可以这样编写:
```sql
DECLARE @AverageScores TABLE (
Subject NVARCHAR(50),
AverageScore DECIMAL(10, 2)
)
INSERT INTO @AverageScores (Subject, AverageScore)
SELECT Subject, AVG(Score) as Average
FROM StudentScores
GROUP BY Subject
WITH CTE_ScoresAboveAverage AS (
SELECT s.StudentID, s.Name, ss.ScoreBySubject
FROM StudentScores s
JOIN @AverageScores a ON s.Subject = a.Subject
WHERE s.ScoreBySubject > a.AverageScore
)
SELECT * FROM CTE_ScoresAboveAverage;
```
这个查询首先创建了一个临时表`@AverageScores`存储每门课的平均分,然后在`CTE_ScoresAboveAverage`公共表表达式(Common Table Expression, CTE)中找出所有分数大于平均分的学生信息。
阅读全文