1

我需要按类别汇总出勤时间,然后按“周”分组。“周”开始日期由该周的星期一定义,但星期日也是有效的。如果类别值在“艺术”或“体育”中,则需要将它们合并为非教育。我还需要能够标记学生达到 120 小时的日期。

我的表结构如下:

CREATE TABLE Attendance (
    ID int,
    Category varchar(20),
    Title varchar(20),
    Date datetime,  
        Hours int, 
    )

INSERT INTO Attendance  VALUES 
(4504498,   'GED Program',  '7/1/2012', 7),
(4504498,   'GED Program',  '7/2/2012', 3),
(4504498,   'GED Program',  '7/3/2012', 3),
(4504498,   'GED Program',  '7/4/2012', 7),
(4504498,   'GED Program',  '7/5/2012', 3),
(4504498,   'GED Program',  '7/8/2012', 3),
(4504498,   'GED Program',  '7/9/2012', 7),
(4504498,   'GED Program',  '7/10/2012',7),
(4504498,   'GED Program',  '7/11/2012',3),
(4504498,   'GED Program',  '7/12/2012',3),
(4504498,   'High School',  '7/1/2012', 7),
(4504498,   'High School',  '7/2/2012', 3),
(4504498,   'High School',  '7/3/2012', 3),
(4504498,   'High School',  '7/4/2012', 3),
(4504498,   'High School',  '7/5/2012', 3),
(4504498,   'High School',  '7/8/2012', 7),
(4504498,   'High School',  '7/9/2012', 3),
(4504498,   'High School',  '7/10/2012',8),
(4504498,   'High School',  '7/11/2012',3),
(4504498,   'High School',  '7/12/2012',7),
(9201052,   'Art',  '7/15/2012',    6),
(9201052,   'Art',  '7/16/2012',    3),
(9201052,   'Art',  '7/17/2012',    7),
(9201052,   'PE',   '7/17/2012',    7),
(9201052,   'PE',   '7/18/2012',    7)

我需要一个看起来像这样的最终结果:

ID  Category    Week of   Total Hours
4504498 GED Program 7/1/2012       26
4504498 GED Program 7/8/2012       23
4504498 High School     7/1/2012       19
4504498 High School     7/8/2012       28
9201052 Non Educational 7/15/2012      30

ID       Day_120_Hours_Reached
356485     6/30/2012
356485     11/15/2012
555666     10/12/2012
555666     2/25/2013

我一直在寻找 Week 函数的示例,该函数将使用 MS Sql Server 从日期中提取“星期”,但我找不到太多信息。任何反馈表示赞赏

4

1 回答 1

1

按周总结:

select  ID
,       Category
,       min(Date) as WeekOf
,       sum(Hours) as TotalHours
from    Attendance
group by
        ID
,       Category
,       datepart(wk, Date)

要找到学生达到 120 小时的第一天:

select  ID
,       min(Date)
from    (
        select  ID
        ,       Date
        ,       sum(Hours) over (partition by ID order by Date) RunningSum
        from    Attendance
        ) as SubQueryAlias
where   RunningSum >= 120
group by
        ID

SQL Fiddle上的实时示例(总和为 60 而不是 120,因此只有一名学生达到。)

如果您使用的是 SQL Server 2005 或更早版本,则不能使用sum() over (). join改为尝试:

select  ID
,       min(Date)
from    (
        select  t1.ID
        ,       t1.Date
        ,       sum(t2.Hours) as RunningSum
        from    Attendance t1
        join    Attendance t2
        on      t1.ID = t2.ID
                and t2.Date <= t1.Date
        group by
                t1.ID
        ,       t1.Date
        ) as SubQueryAlias
where   RunningSum >= 60
group by
        ID;

SQL Fiddle 上的 SQL Server 2005 示例。

于 2013-07-25T22:32:15.590 回答