1

目前我的查询正在获取从当前日期到过去 7 天的数据。我想从上周获取数据。意思是如果今天是 2013-06-20,那么数据应该从上周(2013-06-10 到 2013-06)获取-16)。我搜索了许多论坛的确切答案,但仍然无法找到。

这是我的查询

 SELECT CONVERT(varchar(25),PostDate,107) AS duration, count(*) AS posts
    FROM MDBDetails WHERE 
      DateAdd(dd, 0, DateDiff(dd, 0, PostDate)) <= DateAdd(dd, 0, DateDiff(dd, 0, GETDATE())) AND 
      DateAdd(dd, 0, DateDiff(dd, 0, PostDate)) >= DateAdd(dd, 0, DateDiff(dd, 0, GETDATE())) - 7

          GROUP BY  CONVERT(varchar(25),PostDate,107)
          ORDER BY duration
4

3 回答 3

3

使用DATEDIFF(周, , )

 SELECT CONVERT(varchar(25),PostDate,107) AS duration, count(*) AS posts
 FROM MDBDetails 
 WHERE DATEDIFF(week, PostDate,GETDATE()) = 1
 GROUP BY  CONVERT(varchar(25),PostDate,107)
 ORDER BY duration
于 2013-06-19T19:31:01.900 回答
1

datepart 函数可以为您获取周数。减去 1,你就有了前一周。

SELECT DATEPART(WEEK,GETDATE()) -1

然后,您可以使用例如周数和年份来过滤您的数据。

于 2013-06-19T19:15:37.623 回答
1

以下代码应返回前一周的星期一。

SELECT DATEADD(WEEK, -1, DATEADD(WEEK, DATEDIFF(WEEK, 0, SYSDATETIME()), 0));
于 2013-06-19T19:15:15.710 回答