在SQL Server中获取一周的数字,月份编号和年份的日期范围

时间:2017-04-05 01:56:26

标签: sql sql-server sql-server-2008 tsql date

我创建了一个存储过程,以根据周数,月号和年号显示日期范围内的某些记录。

例如:

Month = 4 [APRIL]
Week  = 2 [Week 2 for APRIL]
Year  = 2017

输出应为:[开始日期应为星期日]

STARTDATE  |  END DATE
4-2-2017   |  4-8-2017

到处搜索,已经很难用这个。

编辑: 我提供了一个示例查询供参考

@Month int,
@Year int,
@WeekNumber int

SELECT
(start date of the week based on week num, month, year) as DATE1,
(end date of the week based on week num, month, year) as DATE2
WHERE
StartDate = (start date of the week based on week num, month, year)
EndDate = (end date of the week based on week num, month, year)

1 个答案:

答案 0 :(得分:2)

也许这会有所帮助。

2008年更新的示例

Declare @Month int = 4
Declare @Year  int = 2017
Declare @Week  int = 2


Select DateR1 = min(RetVal)
      ,DateR2 = max(RetVal)
 From (
        Select *,WkNr = Dense_Rank() over (Order by DatePart(WEEK,RetVal))
         From (Select Top (40) RetVal=DateAdd(DD,-1+Row_Number() Over (Order By Number),cast(str((@Year*10000)+(@Month*100)+1,8) as date)) From  master..spt_values) D
      ) A
 Where WkNr=@Week

<强>返回

DateR1      DateR2
2017-04-02  2017-04-08