【问题标题】:Get date range of a week given a week number, month number, and year in SQL Server在 SQL Server 中获取给定周数、月数和年份的一周的日期范围
【发布时间】:2017-08-30 10:32:57
【问题描述】:

我正在创建一个存储过程来显示基于周数、月数和年数的日期范围内的某些记录。

例如:

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

输出应该是:[Start day should be Sunday]

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)

【问题讨论】:

  • 谢谢。但不幸的是,没有回答我的问题。需要的参数只有周数、月数和年份,而不是完整日期。
  • 您能否包含您将在何处执行查询的示例数据
  • @CurseStacker - 请查看我的编辑。
  • 不,表中的实际数据,您需要获取。

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


【解决方案1】:

也许这会有所帮助。

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

【讨论】:

  • "'DateFromParts' 不是可识别的内置函数名称。" - 我使用的是 2008 R2。
  • @TheNoob 给我一点时间
  • 当然。快速反馈将不胜感激
  • 在少于 7 天的月份的第一周和最后一周工作。谢谢楼主!
  • @TheNoob 很高兴它有帮助。请参阅编辑,我们选择前 40 名而不是前 31 名。为了以防万一,还有一点额外的回旋余地。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
相关资源
最近更新 更多