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

查看:71
本文介绍了从日历周获取月份 (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 ║
╚═══════╝

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

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