根据工作周编号获取月份,季度

时间:2015-08-29 12:20:13

标签: sql-server

我希望根据工作周数来获得月份和季度。

例如:如果工作周数为7,那么它将在Quarter = 1和Month = 2。

同样,如果WK = 35,我应该能够获得quarter = 2和Month = 8

等等。

1 个答案:

答案 0 :(得分:2)

也许是一个处理这个问题的函数.....

功能定义

CREATE FUNCTION dbo.get_Quater_Month (@WeekofYear INT)
RETURNS Table 
AS
RETURN
(WITH X AS
 (
  SELECT TOP (CASE WHEN YEAR(GETDATE()) % 4 = 0 THEN 366 ELSE 365 END) 
      DATEADD(DAY 
             ,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1
             , CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '0101' )      
                      DayNumber
  From master..spt_values
 )
SELECT DATEPART(QUARTER,MIN(DayNumber)) AS [QUARTER]
      ,DATEPART(MONTH,MIN(DayNumber))   AS [Month]
FROM X 
WHERE DATEPART(WEEK,DayNumber) = @WeekofYear)

测试

SELECT * FROM dbo.get_Quater_Month (7)

结果

╔═════════╦═══════╗
║ QUARTER ║ Month ║
╠═════════╬═══════╣
║    1    ║   2   ║
╚═════════╩═══════╝