IIF函数-根据月份返回特定值

时间:2018-08-07 12:54:30

标签: sql ms-access ms-access-2010 iif-function

我正在尝试编写一个查询,该查询将根据某笔交易发生的月份,将Q1,Q2,Q3,Q4填充到“ Quarter”字段中。我正在尝试这种方式,我认为这是相当笨拙:

IIf([Original Date] like “7*” Or [original date] like “8*” or [original date] like “9*”, “Q1”, IIf ([Original Date] like “10*” or [Original Date] like “11*” or [Original Date] like “12*”, “Q2”, IIF([Original Date] like “1*” or [Original Date] like “2*” or [Original Date] like “3*”, “Q3”, IIf([Original Date] like “4*” or [Original Date] like “5*” or [Original Date] like “6*”, “Q4”, Null))))

但是,这不起作用。我在想也许是因为[原始日期]字段是日期/时间数据类型。有没有更好的方法编写此查询?

1 个答案:

答案 0 :(得分:1)

如果[Original Date]是日期,请使用DatePart("q")

(如果没有,请使用CDate()

SELECT "Q" & DatePart("q", [Original Date]) AS Quarter
FROM myTable

哦,等等,您的Q1从7月开始。然后例如修改日期,增加6个月:

SELECT "Q" & DatePart("q", DateAdd("m", 6, [Original Date])) AS Quarter
FROM myTable