在sqlserver中如何查找前一周的数据?

时间:2016-05-20 05:04:29

标签: sql sql-server tsql

我正在尝试以下查询,但它的输出是最后2周的数据,但我只需要在周数据之前持续。

select * from tablename where createddate>=DATEADD(WEEK,-2, GETDATE()) ;

3 个答案:

答案 0 :(得分:2)

只需在WHERE子句中添加另一个条件,将其限制为早于前一周的时间:

SELECT * FROM tablename
WHERE createddate >= DATEADD(WEEK,-2, GETDATE()) AND
      createddate < DATEADD(WEEK,-1, GETDATE())

答案 1 :(得分:1)

从您的评论中我发现,您所谈论的那一周从星期五开始,所以您需要将这些差距天加入您的情况

SELECT * FROM tablename 
WHERE createddate >= DATEADD(ww, DATEDIFF(ww, 4 ,DATEADD(WEEK, -1, GETDATE())), 4)
AND createddate < DATEADD(ww, DATEDIFF(ww, 4 ,DATEADD(WEEK, 0, GETDATE())), 4)

答案 2 :(得分:-1)

此代码是我的定义的当前答案,

 select * from dbo_OrdersCompleteView1 where  S2_DateTimeOrederLines between DATEADD(WEEK,-2, GETDATE()) and DATEADD(WEEK,-1,GETDATE());