我们有一项不同寻常的病假政策,即累计病假时间不得超过 56 小时。我需要编写一个查询来反映这一点。这就是我拥有的
SELECT
t.employeecode, t.LeaveAccrued, PPE, RecordDate,
(CASE
WHEN (SUM(t.LeaveAccrued) OVER (PARTITION BY t.Employeecode ORDER BY RecordDate)) > 56
THEN 56
WHEN (SUM(t.LeaveAccrued) OVER (PARTITION BY t.Employeecode ORDER BY RecordDate)) <= 56
THEN SUM(t.LeaveAccrued) OVER (PARTITION BY t.Employeecode ORDER BY RecordDate)
END) AS accrued_time
FROM
time t
这看起来很有效,但当某人已经达到 56 小时的上限并需要大量时间时,它就会失败。这是失败的结果示例
员工代码 | 应计休假 | 个人防护装备 | 记录日期 | 应计时间 |
---|---|---|---|---|
**** | 0.9000 | 个人防护装备 8 12 22 | 2022-08-16 00:00:00.000 | 54.8169 |
**** | -29.0000 | 个人防护装备 8 12 22 | 2022-08-16 00:00:00.000 | 54.8169 |
**** | 2.2667 | 个人防护装备 8 26 22 | 2022-08-30 00:00:00.000 | 52.0836 |
**** | -5.0000 | 个人防护装备 8 26 22 | 2022-08-30 00:00:00.000 | 52.0836 |
我女儿出生时我请了29个小时的病假。病假时间应该会减少到 27 小时左右。
对于如何处理这个问题有什么建议吗?我一直在基于年度进行计算,并将展期数据放在不同的表中,但我真的很想一劳永逸地解决这个问题。
谢谢
你也可以用另一种方法,先计算运行总计,然后限制值。
SELECT *
, CASE WHEN running_accrued_time > 56 THEN 56 ELSE running_accrued_time END AS running_accrued_time
FROM (
SELECT t.employeecode, t.LeaveAccrued, PPE, RecordDate
, SUM(t.LeaveAccrued) OVER(PARTITION BY t.EmployeeCode ORDER BY RecordDate) AS accrued_time
, SUM(t.LeaveAccrued) OVER(PARTITION BY t.EmployeeCode ORDER BY RecordDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_accrued_time
FROM #time t
) d