SQL中动态生成的列的行总和
这是生成班级月度出勤报告的过程,我想在其中添加一个列作为总计,该列应包含特定学生在两个日期之间的出勤总和,作为参数给出 那么,我应该做些什么来实现这一点,因为简单地计算出席人数就可以计算出表中所有日期的出席人数之和SQL中动态生成的列的行总和,sql,sql-server,sql-server-2014,Sql,Sql Server,Sql Server 2014,这是生成班级月度出勤报告的过程,我想在其中添加一个列作为总计,该列应包含特定学生在两个日期之间的出勤总和,作为参数给出 那么,我应该做些什么来实现这一点,因为简单地计算出席人数就可以计算出表中所有日期的出席人数之和 CREATE PROCEDURE GET_ATTENDANCE_REPORT_FOR_FACULTY @startdate DATE, @enddate DATE, @coursecode nvarchar(10), @subjectcode nvarchar(10) AS B
CREATE PROCEDURE GET_ATTENDANCE_REPORT_FOR_FACULTY
@startdate DATE,
@enddate DATE,
@coursecode nvarchar(10),
@subjectcode nvarchar(10)
AS BEGIN
DECLARE @query as varchar(MAX);
declare @stmt nvarchar(max);
declare @stmt1 nvarchar(max);
with cte (startdate) as
(
select @startdate startdate
union all
select dateadd(DD, 1, startdate)
from cte
where startdate < @enddate
)
select @query = coalesce(@query, '') +
N',coalesce(MAX(CASE when A.[Date] = ''' +
cast(cte.startdate as nvarchar(20)) +
N''' THEN Convert(varchar(10),A.[Attendance]) end), ''NA'') ' +
quotename(convert(char(6), cte.startdate,106))
from cte
where datename(weekday, cte.startdate) <> 'Sunday';
set @query = 'Select S.RollNo AS [Roll No],Concat(FirstName,'' '',LastName) AS Name' + @query + ',sum(Attendance) Total
from Attendance A, Student S, UserDetails U
where A.EnrollmentNo=S.EnrollmentNo and S.EnrollmentNo=U.userID and A.CourseCode=''' + @coursecode + ''' and A.SubjectCode =''' + @subjectcode + '''
and A.Date between ''' + @startdate + ' and ' + @enddate + '''
Group By S.RollNo,U.FirstName,U.LastName';
Execute (@query)
END
使用条件聚合
或者更好的方法,过滤where子句中的日期,还可以使用sp_executesql来参数化动态查询。使查询看起来干净
set @query = 'Select S.RollNo AS [Roll No],Concat(FirstName,'' '',LastName) AS Name' + @query + ',sum(Attendance) Total
from Attendance A, Student S, UserDetails U
where A.EnrollmentNo=S.EnrollmentNo and S.EnrollmentNo=U.userID and A.CourseCode= @coursecode and A.SubjectCode = @subjectcode
and A.[Date] between @startDate and @EndDate
Group By S.RollNo,U.FirstName,U.LastName'
Execute sp_executesql @query, N'@coursecode varchar(100),@subjectcode varchar(100), @startDate date, @EndDate date',@coursecode,@subjectcode, @startDate, @EndDate
使用条件聚合
或者更好的方法,过滤where子句中的日期,还可以使用sp_executesql来参数化动态查询。使查询看起来干净
set @query = 'Select S.RollNo AS [Roll No],Concat(FirstName,'' '',LastName) AS Name' + @query + ',sum(Attendance) Total
from Attendance A, Student S, UserDetails U
where A.EnrollmentNo=S.EnrollmentNo and S.EnrollmentNo=U.userID and A.CourseCode= @coursecode and A.SubjectCode = @subjectcode
and A.[Date] between @startDate and @EndDate
Group By S.RollNo,U.FirstName,U.LastName'
Execute sp_executesql @query, N'@coursecode varchar(100),@subjectcode varchar(100), @startDate date, @EndDate date',@coursecode,@subjectcode, @startDate, @EndDate