如何在SQL中计算WeekOfMonth

时间:2015-08-31 15:13:53

标签: date

尝试计算给定年份的假期以加载DimDate表。 SQL中有一个选项可以计算WeekOfYear Number,但无法找到计算WeekNumberOfMonth的函数。

如何查找给定月份的周数以计算一年中的假期以填充DIMDate表

1 个答案:

答案 0 :(得分:-1)

<强>逻辑 CurrentDateWeek - CurrentDateMonthBeginWeek 给定日期的周数和给定日期的第一周数之间的差异提供一个月的一周

简单的单行SQL语句

Declare @CurrentDate as datetime
set @CurrentDate = '5/31/2014'

Select  (Datepart(week,@CurrentDate) - (Datepart(week,cast(month(@CurrentDate) as varchar) + '/1/' + cast(Year(@CurrentDate) as varchar))) + 1) as WeekOfMonth

存储过程

Declare @CurrentDate as datetime
Declare @BeginWeek as int
Declare @EndWeek as Int
set @CurrentDate = '5/31/2014'

SET @EndWeek = DATEPART(week,eomonth(@CurrentDate))
SET @BeginWeek = Datepart(week,cast(month(@CurrentDate) as varchar) + '/1/' + cast(Year(@CurrentDate) as varchar))
Select  Datepart(week,@CurrentDate) - @BeginWeek + 1
Select @BeginWeek as beginweek
select @EndWeek as endweek
Select Datepart(week,@CurrentDate)

使用上面的逻辑,我们可以用假期日填充DIMDATE表