每周数据过滤器

时间:2011-04-29 01:30:09

标签: tsql

鉴于以下数据:

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

StudentDetails([StudentID],[GivenNames],[姓],[YearLevel],[楼])

问题:我正在尝试为客户生成一份报告,希望了解在特定时期内缺席的前三名以上学生。这个时期可以是从上周到上个月到去年的任何时间。我目前的报告是给他们的:

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)

麻烦的是,他们现在想要一个“每周至今”专栏,但仅针对无法解释的缺席。这意味着他们希望从该特定周的星期一开始查看每个学生的缺席次数。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

这是我的第一次拍摄。每周失踪前3名学生。

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 

答案 1 :(得分: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