2016-11-18 21 views
0

私は、SQL Server 2012を使用して、現在の週のためにこれらのレコードを返す文を持っている:SQL Serverの:先週からDATEDIFF

Employee , Sun , Mon , Tues, Wed, Thurs, Fri, Sat 
-------------------------------------------------- 
Smith  5  8  5 4  8  4 0 
Burt  7  1  8 5  4  4 7 

これは私のSQLで、週の日に開始しますどのように変更して前週を表示するのですか?

SELECT 
    ReproofMidLineBy AS Employee, 
    COUNT(CASE WHEN DATENAME(dw, ReproofMidLineDate)= 'Sunday' THEN 1 END) AS Sun, 
    COUNT(CASE WHEN DATENAME(dw, ReproofMidLineDate)= 'Monday' THEN 1 END) AS Mon, 
    COUNT(CASE WHEN DATENAME(dw, ReproofMidLineDate)= 'Tuesday' THEN 1 END) AS Tues, 
    COUNT(CASE WHEN DATENAME(dw, ReproofMidLineDate)= 'Wednesday' THEN 1 END) AS Wed, 
    COUNT(CASE WHEN DATENAME(dw, ReproofMidLineDate)= 'Thursday' THEN 1 END) AS Thurs, 
    COUNT(CASE WHEN DATENAME(dw, ReproofMidLineDate)= 'Friday' THEN 1 END) AS Fri, 
    COUNT(CASE WHEN DATENAME(dw, ReproofMidLineDate)= 'Saturday' THEN 1 END) AS Sat, 
    COUNT(*) AS TOTAL 
FROM 
    dbo.tblJobLog 
WHERE 
    (ReproofMidLineDate BETWEEN DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE())/7 * 7, 0) 
         AND DATEADD(DAY, DATEDIFF(DAY, 6, GETDATE()- 1)/7 * 7 + 7, 6) 
    ) 
GROUP BY 
    ReproofMidLineBy 

答えて

1

これであなたのwhere句に置き換えます

WHERE 
(
    ReproofMidLineDate BETWEEN DATEADD(WEEK, -1, DATEADD(
     DAY, 
     DATEDIFF(
      DAY, 
      0, 
      GETDATE() 
     )/ 7 * 7, 
     0)) 


    AND DATEADD(WEEK, -1, DATEADD(
     DAY, 
     DATEDIFF(
      DAY, 
      6, 
      GETDATE()- 1 
     )/ 7 * 7 + 7, 
     6 
    )) 
) 
+0

ソート、ありがとう! – Michael

0

Aは本当に簡単な方法は、比較のために1週間を追加することです:あなたはまた、BETWEENの境界から1週間(または7日)を引くことができ

WHERE DATEADD(week, 1, ReproofMidLineDate) BETWEEN . . . 

関連する問題