【问题标题】:MS Access 2010 (Design View): return Monday of the current week with Monday as 1st day of the weekMS Access 2010(设计视图):返回本周的星期一,星期一作为一周的第一天
【发布时间】:2015-04-27 15:01:14
【问题描述】:

我需要让我的 Access 查询始终返回本周的星期一。我在 Google/StackOverflow 上看到了一些解决方案,但它们是用 SQL 编写的,而且我是创建 Access 查询的初学者(我正在使用设计视图来制作它们)。

目标:应将一周视为M T W T F S S。然后,查询应始终返回当前一周的星期一。因此,如果是星期天,它应该仍然返回前一个星期一,NOT下周的星期一。谁能解释如何使用 Access 2010 中的设计视图执行此操作?

【问题讨论】:

  • 这对你有用吗? Date() - (DatePart("w", Date(), 2, 1)-1) .. 您可以将其粘贴到查询设计视图中的 Field 列中。如果它适合你,我可以提供解释。
  • Date() - (WeekDay(Date(), 2) -1)
  • @Invent-Animate 成功了!我很想知道为什么。继续写它作为答案,这样我就可以给它一个绿色的复选标记!
  • 这里有一些关于 datepart 的内容:techonthenet.com/excel/formulas/datepart.php
  • @krish 很好地解释了语法,谢谢!

标签: date ms-access design-view


【解决方案1】:

请记住,在这种情况下,我们正在处理日期,因此如果我们使用 Date() - 1,我们将得到今天前 1 天。

Date()~今天的日期

DatePart(
        "w" - Weekday
        Date() - Today's date
        2 - vBMonday (Access assumes Sunday is the first day of the week, which is why this is necessary.)
        1 - vbFirstJan1 - This gets into using the first week of the year. We could have omitted this, as 1 is the default.
)

-1 - Subtract 1 from the DatePart value.

价值观

Date() = 4/27/2015 (at time of this writing)
DatePart("w",Date(),2,1) = 1
DatePart("w",Date(),2,1)-1 = 0

所以我们有Date()-0...好吧,这有什么了不起的?好吧,让我们看一个更有用的场景,今天的日期不是星期一。

假设今天是 2015 年 4 月 28 日(星期二)

Date() = 4/28/2015
DatePart("w",Date(),2,1) = 2
DatePart("w",Date(),2,1)-1 = 1

所以,从外到内;给我当前的工作日值。 (1 = 星期一,2 = 星期二等),然后从中减去 1 -> 这就是我们需要从当前日期中减去多少天才能回到 weekday 的值 1(星期一)。

【讨论】:

  • 哇,现在说的太有道理了!!感谢您的宝贵时间!
  • 没问题,很高兴我能帮上忙。
【解决方案2】:

这是一个可以做到这一点的函数:

Public Function DatePrevWeekday( _
  ByVal datDate As Date, _
  Optional ByVal bytWeekday As VbDayOfWeek = vbMonday) _
  As Date

' Returns the date of the previous weekday, as spelled in vbXxxxday, prior to datDate.
' 2000-09-06. Cactus Data ApS.

  ' No special error handling.
  On Error Resume Next

  DatePrevWeekday = DateAdd("d", 1 - Weekday(datDate, bytWeekday), datDate)

End Function

由于 vbMonday 是 2 并且您的日期是今天,您可以在查询中使用核心表达式:

PreviousMonday: DateAdd("d",1-Weekday(Date(),2),Date())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-30
    • 2013-06-05
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    相关资源
    最近更新 更多