目前我的查询是从当前日期到过去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
答案 0 :(得分:3)
USE 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
答案 1 :(得分:1)
以下代码应返回上一周的星期一。
SELECT DATEADD(WEEK, -1, DATEADD(WEEK, DATEDIFF(WEEK, 0, SYSDATETIME()), 0));
答案 2 :(得分:1)
datepart函数可以获取周数。减去1,你就有了前一周。
SELECT DATEPART(WEEK,GETDATE()) -1
然后,您可以使用周数和年份来过滤数据。