从日历周获取月份(SQL Server) [英] Get Month from Calendar Week (SQL Server)

查看:172
本文介绍了从日历周获取月份(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!

在此先感谢
Melvin

Thanks in advance, Melvin

推荐答案

查询

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 ║
╚═══════╝

这篇关于从日历周获取月份(SQL Server)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆