考勤系统报告

时间:2018-01-14 10:40:41

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

我正在建立一个考勤系统,我必须在一个月内展示全班的出勤率。

所以我尝试了以下方法,但是我没有得到所需的输出。

我知道我在数据透视查询中做错了,因为我是这类查询的新手,我在其他帖子的帮助下构建了这个查询。

有人可以指导我在这里做错了什么,我该怎么做才能达到预期的效果?

出勤表样本数据 -

Attendance

学生表样本数据 -

Student

UserDetails表样本数据 -

UserDetails

电流输出 -

Current Output

我希望将这些重复记录合并。

CREATE PROCEDURE GET_ATTENDANCE_REPORT_FOR_FACULTY
@startdate DATE,  
@enddate DATE,
@coursecode nvarchar(10),
@subjectcode nvarchar(10)

AS BEGIN

DECLARE @cols as varchar(2000);
DECLARE @cols_select as varchar(MAX);
DECLARE @col varchar(20)
DECLARE @cols_copy varchar(100)
DECLARE @query as varchar(MAX);

WITH cte (startdate)
AS 
(SELECT
        @startdate AS startdate
    UNION ALL
    SELECT
        DATEADD(DD, 1, startdate) AS startdate
    FROM cte
    WHERE startdate < @enddate
)
select c.startdate
into #tempDates
from cte c
where datename(weekday, c.startdate) <> 'Sunday';

SELECT
    @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(CONVERT(CHAR(6),startdate, 106))
        FROM #tempDates
        FOR XML PATH (''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

select @cols_copy = replace(@cols, ',', '')

select @cols_select = SUBSTRING(@cols_select, 2, len(@cols_select) - 1)


SET @query = 'SELECT RollNo,Concat(FirstName,'' '',LastName) AS Name, ' + dbo.fn_convert_cols(@cols) + ' from 
             (
                select S.RollNo,U.FirstName,U.LastName,
                D.startdate,A.Attendance,
                convert(CHAR(6), startdate, 106) PivotDate
                from #tempDates D,Attendance A, Student S, UserDetails U
                where convert(CHAR(6), D.startdate, 106) = convert(CHAR(6), A.Date, 106) and A.EnrollmentNo=S.EnrollmentNo and S.EnrollmentNo=U.userID and A.CourseCode=''' + @coursecode + ''' and A.SubjectCode =''' + @subjectcode + '''
            ) x
           pivot 
           (
                max(Attendance)
                for PivotDate in (' + @cols + ')
           ) p '

EXECUTE (@query)
drop table #tempDates
END

1 个答案:

答案 0 :(得分:1)

我认为你可以使用像这样的旧方法 - 用一些曲调 - ;

;with cte (startdate) as 
(
    select @startdate startdate
    union all 
    select dateadd(DD, 1, startdate) 
    from cte
    where startdate < @enddate
)
select @query = coalesce(@query, '') + 
              N',max(case when A.[Date] = ''' + 
              cast(cte.startdate as nvarchar(20)) + 
              N''' then A.Attendance end) ' + 
              quotename(convert(char(6), cte.startdate,106))
from cte
where datename(weekday, cte.startdate) <> 'Sunday';

set @query = N'select S.RollNo, U.FirstName, U.LastName' + 
            @query +
           N' from Attendance A join Student S on A.EnrollmentNo = S.EnrollmentNo join UserDetails U on A.EnrollmentNo = U.userID' +
           N' where A.CourseCode = ''' + @coursecode + N''' and A.SubjectCode = ''' + @subjectcode + N'''' +
           N' group by S.RollNo, U.FirstName, U.LastName';

exec sp_executesql @query