I'm trying to get the correct SQL code to obtain last Friday's date. A few days ago, I thought I had my code correct. But just noticed that it's getting last week's Friday date, not the last Friday. The day I'm writing this question is Saturday, 8/11/2012 @ 12:23am. In SQL Server, this code is returning Friday, 8/3/2012. However, I want this to return Friday, 8/10/2012 instead. How can I fix this code? Since we're getting to specifics here, if the current day is Friday, then I want to return today's date. So if it were yesterday (8/10/2012) and I ran this code yesterday, then I would want this code to return 8/10/2012, not 8/3/2012.

我正在尝试获取正确的SQL代码以获取上周五的日期。几天前,我以为我的代码是正确的。但只是注意到它已经到了上周的星期五,而不是上周五。我写这个问题的那天是星期六,8/11/2012 @ 12:23 am。在SQL Server中,此代码将于2012年8月3日星期五返回。但是,我希望这会在周五,8/10/2012返回。我该如何修复此代码?由于我们在这里详细说明,如果当天是星期五,那么我想回到今天的日期。所以,如果它是昨天(2012年8月8日)并且我昨天运行了这段代码,那么我希望这段代码返回8/10/2012,而不是8/3/2012。

SELECT DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))

11 个解决方案

#1


11

try this:

尝试这个:

declare @date datetime;
set @date='2012-08-09'
SELECT case when datepart(weekday, @date) >5 then
 DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0)) 
else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0)) end

result:

结果:

2012-08-03 

Example2:

例2:

declare @date datetime;
set @date='2012-08-10'
SELECT case when datepart(weekday, @date) >5 then
 DATEADD(DAY, +4, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0)) 
else DATEADD(DAY, -3, DATEADD(WEEK, DATEDIFF(WEEK, 0, @date), 0)) end

result:

结果:

  2012-08-10 

更多相关文章

  1. Android中RecyclerView的item中控件的点击事件添加删除一行、上
  2. Android Studio中如何编写JNI代码及编译so库
  3. 编译Android4.3内核源代码
  4. Java se之静态代码块、代码块、构造函数执行顺序问题
  5. Java普通代码块,构造代码块,静态代码块区别,执行顺序的代码实例
  6. 编写自己的代码库(javascript常用实例的实现与封装)[转]
  7. 一篇不错的Android Audio架构代码梳理总结
  8. demo_代码注册广播接受者_Service
  9. Android学习笔记--《第一行代码Android》273页代码解密

随机推荐

  1. 对不起,我把APP也给爬了
  2. Python实现数据写入 Excel 的三种模块!
  3. 绝了!Python定时爬取微博热搜+pyecharts动
  4. 这52页pdf,顶10篇python自动化办公文章
  5. 学习C的第五天
  6. 刚学完python自动化系列文章,就接了一单任
  7. 学习C的第四天
  8. 开开心心爬APP,结果一坑连一坑
  9. nginx跳转 去掉工程名
  10. #6.1# 用python画出你的童年回忆