2013-07-23 116 views
3

我需要獲取從sqlserver2008r2記錄,我對獲取記錄本周查詢:如何編寫查詢來獲取最後一週的記錄

select EmpCode,EventDate1 as EventDate,InTime, 
case when OutTime is null then 'N/A' else Outtime end as OutTime from  
TMS_HOURCALC WHERE intime1 
    BETWEEN dateadd(dd,(datediff(DD,-53684,getdate())/7)*7,-53684) 
    AND dateadd(dd,((datediff(dd,-53684,getdate())/7)*7)+7,-53684) 
    and empcode = @empcode 
GROUP BY EmpCode, InTime,OutTime, EventDate1,intime1  
order by intime1; 

請人幫我只能從最後取了上週的記錄週日到週六。

回答

2

列上製作一個計算指的是在where子句中,會帶來可怕的表現。這是一個更好的方法:

select EmpCode,EventDate1 as EventDate,InTime, 
case when OutTime is null then 'N/A' else Outtime end as OutTime from  
TMS_HOURCALC 
WHERE intime1 >= dateadd(dd,(datediff(DD,-1,getdate())/7)*7-7,-1) 
and intime1 < dateadd(dd,((datediff(dd,-1,getdate())/7)*7),-1) 
and empcode = @empcode 
GROUP BY EmpCode, InTime,OutTime, EventDate1,intime1  
order by intime1; 
+1

其實我有一些性能問題!謝謝你的建議 – Hearty

1

確保在你的數據庫@@DateFirst設置爲7(星期日默認)和使用DATEPART()

嘗試使用:

where 
DATEPART(ww, intime1) = DATEPART(ww, GetDate()) 
and 
YEAR(intime1) = YEAR(GetDate()) 
+0

非常感謝! – Hearty

+0

這會給性能問題和年度變化帶來問題(如果描述是正確的 - 從星期日到星期六) –

相關問題