从表中获取最大值(日期)

时间:2012-11-09 13:58:08

标签: sql ms-access jet

希望这很简单。我有一个发送消息表和一个客户表。我正在尝试将最后一条消息的日期发送给客户,但我正在做一场噩梦并无法解决问题!

英文版:告诉我客户收到的最后日期大于DateX且小于DateY的日期。

在我的SQL中:( Msaccess)

SELECT 
  Max(outgoingmessages.outgoingmessagedatetime), 
  outgoingmessages.outgoingmessagecustomerID 
FROM 
  outgoingmessages 
  inner join customers on customers.customerid = 
                          outgoingmessages.outgoingmessagecustomerid 
WHERE  
  (outgoingmessages.outgoingmessagedatetime>#20/Oct/2012# 
  and 
  outgoingmessages.outgoingmessagedatetime < #02/Nov/2012# )
  and 
  outgoingmessages.outgoingmessagecustomerID NOT IN (
    SELECT incomingMessageCustomerID from incomingmessages
  ) 
GROUP BY 
  outgoingmessages.outgoingmessagecustomerID; 

我知道customerid=32已经在05/11发送了一条消息,但查询似乎忽略了这一点并显示了他的旧日期。我确实需要得到customerID和他们最后一条消息的日期。

任何想法?!

================更新

我认为如果我可以说“WHERE MAX(outgoingmessagetime)BETWEEN date1和date2”,该语句会有效...但我不能使用MAX日期。也许我需要一个子查询?

2 个答案:

答案 0 :(得分:0)

为什么不......?

SELECT Top 1 o.outgoingmessagedatetime, o.outgoingmessagecustomerID 
FROM outgoingmessages o
WHERE  o.outgoingmessagedatetime between #2012/10/02# And #2012/11/02#
ORDER BY o.outgoingmessagedatetime Desc

请注意,这不包括11月2日之后发送的邮件。要包含截至11月5日的消息,请说

WHERE  o.outgoingmessagedatetime between #2012/10/02# And #2012/11/05#

重新评论

SELECT  o.outgoingmessagecustomerID, Max(o.outgoingmessagedatetime)
FROM outgoingmessages o
WHERE  o.outgoingmessagedatetime between #2012/10/02# And #2012/11/02#
AND o.outgoingmessagecustomerID NOT IN (
    SELECT outgoingmessagecustomerID FROM outgoingmessages 
    WHERE outgoingmessagedatetime > #2012/11/02#)
GROUP BY o.outgoingmessagecustomerID 

答案 1 :(得分:0)

这个怎么样,起初我不认为客户表是必需的,但看起来好像你可能只想显示与该表中的客户匹配的记录,所以我已经去了这种方法:

SELECT A.MaxDT, A.outgoingmessagecustomerID
FROM
(SELECT Max(O.outgoingmessagedatetime) AS MaxDT, O.outgoingmessagecustomerID
FROM outgoingmessages AS O
WHERE O.outgoingmessagedatetime BETWEEN >#10/21/2012# AND Date()-7
AND O.outgoingmessagecustomerID NOT IN (SELECT incomingMessageCustomerID FROM imcomingmessages)
GROUP BY O.outgoingmessagecustomerID) AS A, customers AS C
WHERE A.outgoingmessagecustomerID = C.customerID

这在派生表中执行MAX计算,然后将结果链接回客户表

Ps:我希望您的字段名称更短^ _ ^