T-SQL 返回多个列的最大值

已知表格如下:

 

StudentName CourseA     CourseB     CourseC
----------- ----------- ----------- -----------
A           60          70          80
B           65          82          80
C           91          77          77

 

要求返回每个学生的最高分:

 

解决方式1:Case When

 

Select StudentName, (case when CourseC > CourseB and CourseC > CourseA then CourseC when CourseB > CourseA and CourseB > CourseC then CourseB else CourseA end) From StudentCourse

 

解决方法2:用户自定义函数

 

CREATE FUNCTION MaxColumnValue ( @p1 int, @p2 int, @p3 int ) RETURNS int AS BEGIN declare @val int if @p1 > @p2 and @p1 > @p3 select @val= @p1 else if @p2 > @p1 and @p2 > @p3 select @val= @p2 else select @val= @p3 return @val END GO ------------------------------ Select StudentName, dbo.MaxColumnValue(CourseA, CourseB, CourseC) as MaxScore From StudentCourse

 

程序运行结果如下:

 

StudentName MaxScore
----------- -----------
A           80
B           82
C           91

(3 row(s) affected)

 

你可能感兴趣的:(function,c)