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 中的周数获取日期
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
