从日历周获取月份 (SQL Server)
我有以下问题:
在 Microsoft 的 SQL Server 中,我有一个表,其中存储了一年和一个日历周(从星期一开始).现在,我想编写一个函数来返回这个日历周开始的月份(即如果星期一是 7 月 31 日,它应该返回7").我还没有找到一个内置函数来完成这个任务,我也不知道如何轻松地实现它.所以我希望你的帮助和想法!
In Microsoft's SQL Server, I have a table where a year and a calendar week (starting with Monday) is stored. Now, I want to write a function which returns the month in which this calendar week starts (i.e. if the Monday is the 31th of July, it should return "7"). I haven't found a built-in function to achieve this task and I have no idea to implement this easily. So I hope for your help and ideas!
提前致谢,梅尔文
推荐答案
查询
DECLARE @WEEK INT;
DECLARE @YEAR INT;
SET @week = 3
SET @year = 2014
SELECT DATEPART(MM,CAST(CONVERT(CHAR(3),
DATEADD(WW,@WEEK - 1,
CONVERT(datetime,'01/01/'+CONVERT(char(4),@Year)))
,100)+ ' 1900' AS DATETIME)) AS [MONTH]
结果
╔═══════╗
║ MONTH ║
╠═══════╣
║ 1 ║
╚═══════╝
相关文章