【问题标题】:calculate Business Day and tie it to date in each month [closed]计算工作日并将其与每个月的日期联系起来[关闭]
【发布时间】:2013-11-27 16:23:16
【问题描述】:

我需要一种方法将一个月的工作日与日历生成器的特定日期联系起来。我能够正确生成日历,但无法填充工作日。

例如,如果 01/01/1999 是星期六,则第一个工作日是 01/04/1999,下一个工作日是 01/05/1999。所以我的桌子需要看起来像这样

Date                Business Date        BusinessDay    BusinessDaysRemaining
01/01/1999          01/04/1999               1                 19  
01/02/1999          01/04/1999               1                 19
01/03/1999          01/04/1999               1                 19
01/04/1999          01/04/1999               1                 19
01/05/1999          01/05/1999               2                 18
01/06/1999          01/06/1999               3                 17
Etc...

然后这将在下个月重新开始。在其他月份(和周末),营业日期可以追溯到周末前的星期五,这只是我想要完成的一个例子。

我不知道从哪里开始,所以任何帮助将不胜感激。

这是在 MS SQL 2008 R2 中

【问题讨论】:

  • MS SQL 2008 V2.我也将其添加到我的问题中。
  • 我认为结束这个问题的投票是不合理的。如果它关闭了,我希望其他人能和我一起重新打开它。
  • 你的餐桌有假期栏吗?如果没有,您可能需要它,除非您认为这些是工作日。
  • 是的,假期在主日历表中,并且已经从我创建的子表中的日期中删除。因此,此表中的 Business Dates 列表已经删除了 Weekends 和 Holidays。
  • 如果 01/01/1999 是星期六,那么 01/03/1999(该星期六之后的星期一)不是工作日吗?如果您说您已经取消了假期,那么您的预期表格中的 01/03/1999 怎么会以 01/04/1999 作为 01/03/1999 的营业日期?

标签: sql sql-server date calendar


【解决方案1】:

对于这个答案,我创建了一个名为 Calendar 的表。主键是 TheDate 数据类型日期。其他字段是 HolidayName (nullable varchar)、BusinessDayOfMonth tinyint default 0 和 BusinessDaysRemainingInMonth tinyint default 0。然后我输入了 2013 年 12 月的记录,其中有两个假期 - 圣诞节和节礼日。

这是我的更新。

update Calendar
set BusinessDayOfMonth = therank
from Calendar join
(
select TheDate
, rank() over 
(partition by cast(datepart(year, thedate) as varchar) +  cast(datepart(month, thedate) 
as varchar) 
order by thedate) therank

from Calendar
where HolidayName is null
and DATEPART(dw,thedate) between 2 and 6  -- Monday to Friday
) temp on Calendar.TheDate = temp.TheDate


declare @BusinessDays as tinyint
set @BusinessDays =
(select count(1) BusinessDays
from Calendar
where BusinessDayOfMonth > 0
)

update Calendar
set BusinessDaysRemainingInMonth = @BusinessDays - BusinessDayOfMonth
where BusinessDayOfMonth > 0

在您的情况下,您当然需要一个日期范围。另外,您将不得不更新周末和节假日的 BusinessDaysRemainingInMonth 字段。如果您需要这方面的帮助,我建议单独提出一个问题。

【讨论】:

  • 我不得不做一些小的修改,但这确实有效。谢谢丹!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-26
相关资源
最近更新 更多