Get dates from a week number in T-SQL(从 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/2009 和 3/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 中的周数获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 T-SQL 中的周数获取日期
基础教程推荐
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在多列上分布任意行 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
