2011-04-29 61 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