在sql中动态生成列的行总和

时间:2018-01-15 08:33:01

标签: sql sql-server sql-server-2014

这是生成课程每月出勤报告的过程,我想再添加一列作为“总计”,其中应包含特定学生在日期之间的出勤总和,作为参数给出。

那么我应该怎样做才能实现这一点,因为简单地做总和(出勤)将会出现在表中所有日期的出席总和?

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

1 个答案:

答案 0 :(得分:3)

使用Conditional Aggregation

sum(case when date between @startdate and @enddate then Attendance else 0 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