在SQL中生成学生出勤报告时忽略星期日

时间:2018-01-12 21:13:20

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

此代码为我提供了作为参数传递的两个日期之间的出勤报告。 我将分别通过从C#代码中选择的月份的日期。

但是我想在生成出勤报告时跳过星期日。我怎样才能做到这一点?

DECLARE @startdate date = '20180109';
DECLARE @enddate date = '20180112';
DECLARE @cols as varchar(2000);
DECLARE @query as varchar(MAX);

WITH cte (startdate)
AS 
(SELECT
        @startdate AS startdate
    UNION ALL
    SELECT
        DATEADD(DAY, 1, startdate) AS startdate
    FROM cte
    WHERE startdate < @enddate
)
select c.startdate
into #tempDates
from cte c

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

SET @query = 'SELECT RollNo,FirstName,LastName, ' + @cols + ' from 
             (
                select S.RollNo,U.FirstName,U.LastName,
                D.startdate,
                convert(CHAR(10), startdate, 120) PivotDate
                from #tempDates D,Attendance A, Student S, UserDetails U
                where D.startdate = A.Date and A.EnrollmentNo=S.EnrollmentNo and A.EnrollmentNo=U.userID
            ) x
           pivot 
           (
                count(startdate)
                for PivotDate in (' + @cols + ')
           ) p '

EXECUTE (@query)
drop table #tempDates

1 个答案:

答案 0 :(得分:2)

如何更改#TempDates

select c.startdate
into #tempDates
from cte c
where datename(weekday, c.startdate) <> 'Sunday';

这假定您的国际化设置设置为&#34;英语&#34;。