Home >Database >Mysql Tutorial >查询给定日期所在星期的上一个星期日(星期日为第一天)sql语句

查询给定日期所在星期的上一个星期日(星期日为第一天)sql语句

WBOY
WBOYOriginal
2016-06-07 17:47:421315browse

查询给定日期所在星期的上一个星期日(星期日为第一天)sql语句

declare @date  datetime
set @date= getdate()
--思路:当前日志所在星期的星期日再减1周
--datepart(weekday,date)的返回值与@@datefirst相关
set datefirst 7 -- 或者设置为美国英语set language us_english; (星期日为第一天)
select dateadd(week,-1,dateadd(day,1-datepart(weekday,@date),@date)) as '上个星期第一天,星期日'
--一周等于7天
select dateadd(day,-7,dateadd(day,1-datepart(weekday,@date),@date)) as '上个星期第一天,星期日'
--简化
select dateadd(day,-6-datepart(weekday,@date),@date) as '上个星期第一天,星期日'
--上个星期日,与sql server语言版本或@@datefirst无关
select dateadd(week,-1+datediff(week,-1,@date),-1) as '上个星期日'
--或者
select dateadd(week,datediff(week,6,@date),-1) as '上个星期日'
go
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn