【发布时间】:2016-10-29 23:43:52
【问题描述】:
希望为两班(蓝队/红队)的人员配备模型生成一个动态日历,即 4 天上班/4 天休息。我希望能够根据静态日期捕获未来的日期和过去的日期。
例如,如果蓝队的第一天轮班是 2016 年 6 月 1 日,最后一天是 6/4/2016,而红队的第一天轮班是 2016 年 6 月 5 日,最后一天现在是 6/8/2016,如何在 SQL Server 中创建向前和向后的滚动视图?
基本上我想知道在特定的一天应该为哪个团队配备人员,这将允许我计算人员配备百分比以查看谁休假/生病/等。如果我可以构建滚动日历视图,我可以将其用作衡量员工绩效的驱动因素。
理想情况下,我想动态生成这个视图:
- 蓝队静态轮班开始日期 - 6/1/2016 06:00:00 AM
- 红队静态轮班开始日期 - 6/5/2016 06:00:00 AM
样本输出:
Shift | Date
Blue | 5/24/2016 06:00:00 AM
Blue | 5/25/2016 06:00:00 AM
Blue | 5/26/2016 06:00:00 AM
Blue | 5/27/2016 06:00:00 AM
Red | 5/28/2016 06:00:00 AM
Red | 5/29/2016 06:00:00 AM
Red | 5/30/2016 06:00:00 AM
Red | 5/31/2016 06:00:00 AM
Blue | 6/1/2016 06:00:00 AM
Blue | 6/2/2016 06:00:00 AM
Blue | 6/3/2016 06:00:00 AM
Blue | 6/4/2016 06:00:00 AM
Red | 6/5/2016 06:00:00 AM
Red | 6/6/2016 06:00:00 AM
Red | 6/7/2016 06:00:00 AM
Red | 6/8/2016 06:00:00 AM
Blue | 6/9/2016 06:00:00 AM
Blue | 6/10/2016 06:00:00 AM
Blue | 6/11/2016 06:00:00 AM
Blue | 6/12/2016 06:00:00 AM
Red | etc...
提前感谢您的任何建议。
更新:
使用来自link的代码
我能够生产到滚动的未来日期:
; with samples as
(
-- start with 6/1/2016
select cast( '06-01-2016 06:00' as datetime ) as sample
union all
-- add days up to the desired end date
select dateadd( day, 1, sample )
from samples
where sample <= '2020-12-31'
),
extendedsamples as
(
-- calculate the number of days since the beginning of the first shift on 6/1/2016.
select
sample, datediff( day, '06-01-2016 06:00', sample ) as days
from samples
),
shifts as
(
-- calculate the shifts for each day.
select
*,
case when ( days + 1 ) % 8 between 1 and 4 then 'Blue' else 'Red' end as shifts
from extendedsamples
)
select
shifts,
sample
from
shifts
option (maxrecursion 0)
我现在需要弄清楚如何生成这段代码的历史片段,以便我可以捕获以前的人员配备百分比......
更新 2:
所以看起来如果我只是反转一些函数和数字并默认为蓝队 2016 年 6 月 1 日静态班次的前一天。我也可以生成历史视图。
; with samples as
(
-- start with 5/31/2016 to pull historical.
select cast( '05-31-2016 06:00' as datetime ) as sample
union all
-- subtract days back to the desired start date.
select dateadd( day, -1, sample )
from samples
where sample >= '2015-01-01'
),
extendedsamples as
(
-- calculate the number of days before the beginning of the first blue shift on 6/1/2016.
select sample, datediff( day, '05-31-2016 06:00', sample ) as days
from samples
),
shifts as
(
-- calculate the shifts for each day.
select
*,
case when ( days - 1 ) % 8 between -4 and -1 then 'Red' else 'Blue' end as shifts
from extendedsamples
)
select
shifts,
sample
from
shifts
option (maxrecursion 0)
我现在可以将这些结果转储到静态表中以供参考。有没有更好的解决方法?如果没有,我会继续处理并将此问题标记为已回答。
【问题讨论】:
标签: sql-server date dynamic calendar