从 T-SQL 中的周数获取日期 [英] Get dates from a week number in T-SQL

查看:57
本文介绍了从 T-SQL 中的周数获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Microsoft SQL Server 中,我有一个周数

In Microsoft SQL Server, I have a week number

(from DATEPART(wk, datecol)) 

但我想做的是把它改回那一周的日期跨度.

But what I would like to do is turn this back into the date span for that week.

例如

SELECT DATEPART(wk, GETDATE())

产生 10.我想从这个数字推导出 3/1/20093/7/2009.

yields 10. I would like to derive 3/1/2009 and 3/7/2009 from this number.

这可能吗?

推荐答案

Quassnoi 的回答有效,但如果日期是在一天中间的日期(他的一周开始离开如果您在一天中间使用一个时间,那么您比您需要的时间提前一天 - 您可以使用 GETDATE() 进行测试.

Quassnoi's answer works, but kind of leaves you on the hook for cleaning up the dates if they are dates in the middle of the day (his start of week leaves you one day earlier than you need to be if you use a time in the middle of the day -- you can test using GETDATE()).

我过去用过这样的东西:

I've used something like this in the past:

SELECT 
   CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL), DATECOL)), 101),
   CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL) - 6, DATECOL)), 101)

这样做的一个附带好处是,通过使用 @@DATEFIRST,您可以处理非标准的一周开始日(默认为星期日,但使用 SET @@DATEFIRST 您可以更改此设置).

A side benefit of this is that by using @@DATEFIRST you can handle nonstandard week starting days (the default is Sunday, but with SET @@DATEFIRST you can change this).

SQL Server 中的简单日期操作必须如此神秘,这似乎很疯狂,但是你去...

It seems crazy that simple date manipulation in SQL Server has to be this arcane, but there you go...

这篇关于从 T-SQL 中的周数获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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