SQL Server - 选择本周内的行

时间:2013-04-29 09:19:30

标签: sql sql-server date

我有以下代码:

SELECT COUNT(INTERVIEW_ID) 
FROM Interviews AS i INNER JOIN CVsSent AS cvt ON i.CVSENT_ID = cvt.CVSENT_ID  
WHERE cvt.EMP_ID = e.EMP_ID 
AND (i.DATE_TIME >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) 
AND i.DATE_TIME < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)))
AS INTERVIEW_COUNT_DAY

选择今天的计数。我需要一个查询来选择本周的计数,从星期六(第7天)结束的星期日(第1天)开始,而不是过去7天。这可能吗?

2 个答案:

答案 0 :(得分:2)

试试这个 -

DECLARE 
      @FirstDayOfWeek DATETIME
    , @LastDayOfWeek DATETIME

SELECT 
      @FirstDayOfWeek = DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 6)
    , @LastDayOfWeek = DATEADD(wk, DATEDIFF(wk, 5, GETDATE()), 5)

SELECT 
      INTERVIEW_COUNT_DAY = COUNT(INTERVIEW_ID)
    , DATEPART(weekday, DATE_TIME)
FROM dbo.Interviews i 
JOIN dbo.CVsSent cvt ON i.CVSENT_ID = cvt.CVSENT_ID  
WHERE cvt.EMP_ID = e.EMP_ID 
    AND (i.DATE_TIME >= @FirstDayOfWeek AND i.DATE_TIME < @LastDayOfWeek)
GROUP BY DATEPART(weekday, DATE_TIME)

<强>更新:

DECLARE @PrevWeek DATETIME = DATEADD(DAY, -7, GETDATE())

DECLARE
      @FirstDayOfPrevWeek DATETIME = DATEADD(wk, DATEDIFF(wk, 6, @PrevWeek), 6)
    , @LastDayOfPrevWeek DATETIME = DATEADD(wk, DATEDIFF(wk, 5, @PrevWeek), 5)

SELECT @FirstDayOfPrevWeek, @LastDayOfPrevWeek

答案 1 :(得分:1)

试试这个:
第一天#34;星期日&#34;使用:

DATEADD(Week, DATEDIFF(WEEK, '19000101', '29-Apr-2013'), '19000101') - 1 

并且最后一天和#34;星期六&#34;使用:

DATEADD(WEEK, DATEDIFF(WEEK, '19000101', '29-Apr-2013') + 1, '19000101') - 2