2010-11-15 49 views
1

我想從當前星期內的日期字段具有值的表中選擇所有行。我想要從當週的星期一到當天的行。選擇具有本週內值的日期字段的行

例子:

 
ID adate 
--------------- 
1 11-11-2010 
2 12-11-2010 
3 13-11-2010 
4 14-11-2010 
5 15-11-2010 

我想在這種情況下,行是:

 
ID adate 
--------------- 
4 14-11-2010 //this week's Monday 
5 15-11-2010 //till today 

回答

2

這將工作從星期日到星期六一週。從週一如果你想星期你必須適應它星期日:

select * 
    from myTable 
where aDate between 
     cast('now' as date) - extract(weekday from cast('now' as date)) --prev sunday 
     and 
     cast('now' as date) - extract(weekday from cast('now' as date)) + 6 --next saturday 
     ; 
+0

太棒了,謝謝! – 2010-11-15 22:45:41

+0

YVW,享受它。 :) – jachguate 2010-11-15 23:20:32

1

我寫在MS SQL:

declare @today as datetime 
declare @first_day_of_week datetime 
set @today = convert(varchar, getDate(), 101) 
set @first_day_of_week = dateadd(day, -(DATEPART(WEEKDAY, @today) - 1), @today) 
select * 
from [table] 
where adate between @first_day_of_week and @today 

星期日是一週的開始。

+0

爲了提高效率,我做了查詢之外的日期計算,這樣的計算不重複表中的每一個記錄,特別是如果你有大量的記錄。 – 2010-11-15 22:34:31

相關問題