我不知道这个功能有什么问题

时间:2011-03-14 01:51:12

标签: sql database function

嘿......我有这个数据库,我需要创建一个函数来返回通过主题的学生的百分比,但我不知道我做错了什么...你能帮我吗?这是我的图Diagram,这是我的函数......

create function fnPassedStudents(@Semester varchar(7),@CodSubjects varchar(5))
returns @Passed
TABLE (
Semester varchar(7),
Cod_Subjects varchar(5),
Name_Subjects varchar(80),
Nro_Students int,
Nro_Passed float,
Nro_Failed float,
PercentagePassed varchar(4))
as
begin
declare @NroPassed float
select @NroPassed = count(M.Cod_Student)
from Matricula M inner join Subjects A on M.Cod_Subjects = A.Cod_Subjects
Where M.Semester=@Semester and M.Cod_Subjects = @CodSubjects and M.Grade>=10

insert into @Passed 
select M.Semester, A.Cod_Subjects, A.Name_Subjects, COUNT(M.Cod_Student) as Total, 
@NroPassed as Passed, (COUNT(M.Cod_Student) - @NroPassed) as Failed,
((@NroPassed * 100)/(count(M.Cod_Student))) as PercentagePassed
from Matricula M inner join Subjects A on M.Cod_Subjects = A.Cod_Subjects
Group by M.Semester, A.Cod_Subjects, A.Name_Subjects
return  
end
go

我不确定这些信息是否足够......但请耐心等待我会添加你需要的任何东西......谢谢!

1 个答案:

答案 0 :(得分:3)

create function fnPassedStudents(@Semester varchar(7),@CodSubjects varchar(5))
returns @Passed
TABLE (
Semester varchar(7),
Cod_Subjects varchar(5),
Name_Subjects varchar(80),
Nro_Students int,
Nro_Passed float,
Nro_Failed float,
PercentagePassed varchar(4))
as
begin
insert into @Passed 
select
    M.Semester,
    A.Cod_Subjects,
    A.Name_Subjects,
    count(distinct M.cod_student),
    count(case when M.Grade>=10 then 1 end),
    count(*) - count(case when M.Grade>=10 then 1 end),
    count(case when M.Grade>=10 then 1 end) / count(distinct M.cod_student) * 100
from Matricula M
inner join Subjects A on M.Cod_Subjects = A.Cod_Subjects
Group by M.Semester, A.Cod_Subjects, A.Name_Subjects
return  
end
go

成分<​​/ P>

count(distinct M.cod_student) - 参加一个学期/科目的学生人数 case when M.Grade>=10 then 1 end - 传递时产生1,否则返回null。 NULL不是COUNTed count(*) - count(case..) - 传递=失败的补充