访问sql criteria date 3个月前

时间:2017-09-05 09:32:40

标签: sql date ms-access format criteria

我需要过滤一个表格,只显示3个月前的结果。所以如果是八月,请告诉我五月。

这是我的查询sql代码:

SELECT tblAppointment.WorkID, tblAppointment.AppointmentDate, tblCustomer.CustomerID 
FROM tblWork INNER JOIN (tblCustomer INNER JOIN tblAppointment ON tblCustomer.CustomerID = tblAppointment.CustomerID) ON tblWork.WorkID = tblAppointment.WorkID 
GROUP BY tblAppointment.WorkID, tblAppointment.AppointmentDate, tblCustomer.CustomerID 
HAVING (((tblAppointment.WorkID)=3) AND ((tblAppointment.AppointmentDate) Between Format(DateAdd("m",-3,Date()),"m") And Format(DateAdd("m",-4,Date()),"m"))) 
ORDER BY tblAppointment.AppointmentDate, tblCustomer.CustomerID;

我收到了错误消息。我正在努力修复HAVING part。

请帮忙。

2 个答案:

答案 0 :(得分:1)

始终将日期作为日期处理,而不是文本:

SELECT 
    tblAppointment.WorkID, 
    tblAppointment.AppointmentDate, 
    tblCustomer.CustomerID 
FROM 
    tblWork 
INNER JOIN 
    (tblCustomer 
    INNER JOIN tblAppointment 
    ON tblCustomer.CustomerID = tblAppointment.CustomerID) 
    ON tblWork.WorkID = tblAppointment.WorkID 
WHERE
    tblAppointment.AppointmentDate 
    Between 
        DateSerial(Year(Date()), Month(Date())-3, 1)
    And 
        DateSerial(Year(Date()), Month(Date())-2, 0)
GROUP BY 
    tblAppointment.WorkID, 
    tblAppointment.AppointmentDate, 
    tblCustomer.CustomerID 
HAVING 
    tblAppointment.WorkID=3
ORDER BY 
    tblAppointment.AppointmentDate, 
    tblCustomer.CustomerID;

答案 1 :(得分:0)

根据您的错误和代码,看起来您正在尝试将日期与字符串进行比较。无论Having / and DatePart("m", Date()) - DatePart("m", tblAppointment.AppointmentDate)) = 3 结构是否必要,请将日期比较更改为:

AND (
        (
            Year(Date()) = Year(tblAppointment.AppointmentDate) 
            AND 
            DatePart("m", Date()) - DatePart("m", tblAppointment.AppointmentDate) = 3
        )
    OR
        (
            Year(Date()) > Year(tblAppointment.AppointmentDate) 
            AND
            DatePart("m", Date()) + 12 - DatePart("m", tblAppointment.AppointmentDate) = 3
        )
    )

您可能需要修改以涵盖年初/年末的案例。

{{1}}