1

我正在寻找一种方法来计算学生缺勤的不同时期:

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

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有2个周期重叠,也没有间隙,所以它必须被认为是1个缺席周期

谁能帮我写一个查询?

4

2 回答 2

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
于 2011-07-27T14:50:41.017 回答
1

我不确定我是否理解你的想法,但如果你想计算学生的缺勤情况,也许这就是你的方式。

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

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

于 2011-07-27T13:52:54.000 回答