SQL计算学生的明显缺勤期

时间:2011-07-27 13:40:03

标签: sql gaps-and-islands

我正在寻找一种方法来计算学生缺席时没有差距的不同时期:

每当学生缺席时,我会在缺席表中创建一条记录,有些缺席可能会重叠,有些缺席会延长之前的缺席。

StuId    StrPer       EndPer
------   -----------  -----------
111111   2011-01-10   2011-01-15
222222   2011-02-01   2011-02-05
222222   2011-02-06   2011-02-08
333333   2011-04-07   2011-04-14
444444   2011-04-20   2011-04-25
444444   2011-04-23   2011-04-28
111111   2011-05-01   2011-05-03

现在我想计算具有间隙的唯一缺勤期数,结果应为:

StuId   NbrAbs
------  ------
111111  2
222222  1
333333  1
444444  1

111111有两个缺席期,

之间存在差距

222222也有两个缺席期但没有间隙,因此必须将其视为1个缺席期

333333只有1个缺席期

444444有两个重叠的周期,也没有间隙,因此必须将其视为1个缺席期

有人可以帮我写一个查询吗?

2 个答案:

答案 0 :(得分:1)

我不确定我理解你的想法,但如果你想知道学生的缺席,也许这就是你的方式。

SELECT `StudId`, COUNT(`StudId`) as `NbrAbs` FROM `AbsenseTableName` GROUP BY `StdId`

我没有测试代码。但这是主要的想法。

答案 1 :(得分:1)

假设SQL 2005+应该可行:

SELECT '111111' as stuid,'2011-01-10' as start_date,'2011-01-15' as end_date into #data UNION ALL
SELECT '222222','2011-02-01','2011-02-05' UNION ALL
SELECT '222222','2011-02-06','2011-02-08' UNION ALL
SELECT '333333','2011-04-07','2011-04-14' UNION ALL
SELECT '444444','2011-04-20','2011-04-25' UNION ALL
SELECT '444444','2011-04-23','2011-04-28' UNION ALL
SELECT '111111','2011-05-01','2011-05-03' 

;with periods as
(
select 
stuid
,start_date
,end_date
,row_number() OVER (PARTITION BY stuid ORDER BY end_date ASC) as period_number
FROM #data
)
,periods2 AS
(
SELECT 
p1.stuid
,p1.start_date
,p1.end_date
,p1.period_number
,ISNULL(DATEDIFF(DD,p1.end_date,p2.start_date),1) as period_gap
from periods p1
LEFT OUTER JOIN periods p2 on p2.stuid = p1.stuid
AND p2.period_number = p1.period_number + 1
)
SELECT 
stuid
,count(period_gap) as number_discrete_absences
FROM periods2
WHERE period_gap > 0
GROUP BY stuid