SQL Server 2005对T-SQL的增强之在聚合函数的后面使用over关键字
if object_id('student_class_grade','U') is not null drop table student_class_grade;
GO
create table student_class_grade ( student_id int, --学生id class_no int, --班级编号 grade int --成绩 );
GO
INSERT INTO student_class_grade VALUES(1,1,90);
INSERT INTO student_class_grade VALUES(2,1,85);
INSERT INTO student_class_grade VALUES(3,1,80);
INSERT INTO student_class_grade VALUES(4,1,80);
INSERT INTO student_class_grade VALUES(5,1,90);
INSERT INTO student_class_grade VALUES(6,1,75);
INSERT INTO student_class_grade VALUES(7,1,89);
INSERT INTO student_class_grade VALUES(11,2,90);
INSERT INTO student_class_grade VALUES(12,2,85);
INSERT INTO student_class_grade VALUES(13,2,80);
INSERT INTO student_class_grade VALUES(14,2,80);
INSERT INTO student_class_grade VALUES(15,2,90);
INSERT INTO student_class_grade VALUES(16,2,75);
INSERT INTO student_class_grade VALUES(17,2,100);
sql server2005中我们可以用简单的一个语句完成这个任务partition by 后面跟聚合列,如下:
select student_id,class_no,grade ,class_avg_grade = AVG(grade) over(partition by class_no) from student_class_grade
若是在2000中,我们不得不使用子查询,查询要复杂一些
select scg.student_id ,scg.class_no ,scg.grade ,t_avg. class_avg_grade from student_class_grade scg INNER JOIN (select class_no,class_avg_grade = AVG(grade) from student_class_grade group by class_no) t_avg ON t_avg.class_no = scg.class_no
同样其他聚合函数SUM,COUNT,MAX,MIN也可以使用类似用法。