2011-04-29 58 views
2

鉴于以下数据:周为日期数据滤波器

StudentAbsences([StudentID],[DateAbsent],[ReasonCode])

StudentDetails([StudentID],[GivenNames],[姓氏] ,[YearLevel],[House])

问题:我想为客户端生成一份报告,希望看到在特定时间段内缺席的前3名学生。这段时间可以从上周到上个月到去年的任何地方。我现在的报告给他们:

Student's Name (concatenation of GivenNames and Surname) 
Unexplained (Number of Unexplained Absences during that particular period) 
All Year to Date (The count of ALL the different types of Absence reasons for YTD) 
Year Level (The student's Year Level) 

麻烦的是,他们现在希望有一个“周以日期”一栏也只是为无故缺席。这意味着他们希望看到每个学生从该周一开始的缺勤数量。

有什么建议吗?

回答

0

这是我第一次拿。一周内失去排名前三的学生。

DECLARE @StartDate DateTime, 
     @EndDate DateTime 

SELECT @StartDate=DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0), @EndDate=GetDate() 

SELECT D.* 
FROM StudentDetails D 
INNER JOIN 
(SELECT TOP 3 StudentID 
FROM StudentAbsences 
WHERE DateAbsent Between @StartDate and @EndDate 
GROUP BY StudentID, CONVERT (nvarchar(10),DateAbsent, 102) 
ORDER BY COUNT(CONVERT (nvarchar(10),DateAbsent, 102)) DESC) A ON A.StudentID = D.StudentID 
0

尝试...

DECLARE 
    @today datetime, 
    @monday datetime 

SELECT 
    @today = CONVERT(varchar(10), GETDATE(), 101), 
    -- modulus is necessary, because report may be run on Sunday 
    @monday = DATEADD(day, -1 * ((DATEPART(weekday, @today) + 5) % 7), @today) 

SELECT @today, @monday 

SELECT 
    SA.StudentId, 
    // OtherData..., 
    T.WeekToDate 
FROM 
    StudentAbsences SA 

    INNER JOIN StudentDetails SD 
    ON SA.StudentId = SD.StudentId 

    CROSS APPLY 
    (
    SELECT WeekToDate = COUNT(*) 
    FROM StudentAbsences 
    WHERE 
     Studentid = SA.StudentId 
     AND 
     DateAbsent >= @monday 
     AND 
     ReasonCode = 'Unexplained' -- substitute with actual unexplained code 
) T