选择日期字段具有本周内值的行

时间:2010-11-15 21:02:43

标签: sql datetime date firebird

我正在尝试从表中选择日期字段在当前周内具有值的所有行。我想要从当周的星期一到当天的行。

示例:

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 个答案:

答案 0 :(得分: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
         ;

答案 1 :(得分: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

周日是本周的开始。