SQL 语句 HAVING MAX(some+thing)=some+thing
我在使用 Microsoft Access 2003 时遇到问题,它抱怨以下语句:
select cardnr
from change
where year(date)<2009
group by cardnr
having max(time+date) = (time+date) and cardto='VIP'
我想要做的是,对于表中每个不同的 cardnr 更改,找到 2009 年之前最新(时间+日期)的行,然后只需选择带有 cardto='VIP' 的行。
这个 validator 说没问题,Access 说没问题。
这是我收到的消息:“您尝试执行的查询不包含指定表达式 'max(time+date)=time+date and cardto='VIP' and cardnr=' 作为聚合函数的一部分。”
有人可以解释一下我做错了什么以及正确的方法吗?谢谢
注意:字段和表名称已翻译,不会与任何保留字冲突,我对这些名称没有任何疑问。
I'm having trouble with Microsoft Access 2003, it's complaining about this statement:
select cardnr
from change
where year(date)<2009
group by cardnr
having max(time+date) = (time+date) and cardto='VIP'
What I want to do is, for every distinct cardnr in the table change, to find the row with the latest (time+date) that is before year 2009, and then just select the rows with cardto='VIP'.
This validator says it's OK, Access says it's not OK.
This is the message I get: "you tried to execute a query that does not include the specified expression 'max(time+date)=time+date and cardto='VIP' and cardnr=' as part of an aggregate function."
Could someone please explain what I'm doing wrong and the right way to do it? Thanks
Note: The field and table names are translated and do not collide with any reserved words, I have no trouble with the names.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这样想 - HAVING 在聚合完成后应用。
因此它不能与未聚合的表达式进行比较(无论是时间+日期还是cardto)。
但是,要获取最后一个时间和日期(原理与获取与其他聚合函数相关的行相同)时间和日期,您可以执行以下操作:(
假设时间字段上的日期部分对于所有记录都是相同的;有两个日期/时间的字段不符合您的最佳利益,并且在某些情况下使用字段名称的保留字可能会适得其反)
它之所以有效,是因为子查询仅在外部查询中您感兴趣的记录上进行过滤。
对外部查询应用相同的年份(日期)<200和cardto='VIP'可以进一步提高性能。
Try to think of it like this - HAVING is applied after the aggregation is done.
Therefore it can not compare to unaggregated expressions (neither for time+date, nor for cardto).
However, to get the last (principle is the same for getting rows related to other aggregated functions as weel) time and date you can do something like:
(assuming that date part on your time field is the same for all the records; having two fields for date/time is not in your best interest and also using reserved words for field names can backfire in certain cases)
It works because the subquery is filtered only on the records that you are interested in from the outer query.
Applying the same year(date)<200 and cardto='VIP' to the outer query can improve performance further.