SELECT IN 失败 - 大型数据集
我正在尝试评估在我们的系统中给定月份内启动交易的次数以进行对账过程。
交易参考可以在上个月创建,因此我尝试从最终计数中排除这些交易 - 第一个想法是使用“WHERE IN”类型的方法,但结果始终为 0,这绝对是错误的,因为当我单独执行查询,子查询中存在应排除的条目。
我读过“WHERE IN”类型查询并不可靠,特别是当子查询中返回大量数据集时,但我不知道如何重新设计这个查询以实现这种情况下的目标,如果这种情况继续下去这样做的方式似乎是有缺陷的。
当前查询如下所示 - 感谢您的帮助:
SELECT Count(DISTINCT TransactionRef)
FROM Payments
WHERE Month(PaymentDate) = 8
AND Year(PaymentDate) = 2011
AND TransactionRef NOT IN
(SELECT DISTINCT TransactionRef
FROM Payments WHERE PaymentDate < '20110801')
编辑 好吧,进一步回答,似乎空值让我错了......谢谢 - 这是编辑后的代码,以防将来有人在这里绊倒:
SELECT Count(DISTINCT TransactionRef)
FROM Payments
WHERE Month(PaymentDate) = 8
AND Year(PaymentDate) = 2011
AND TransactionRef NOT IN
(SELECT DISTINCT TransactionRef
FROM Payments WHERE TransactionRef IS NOT NULL AND PaymentDate < '20110801')
I'm attempting to evaluate how many times a transaction is started in a given month in our system for a reconciliation process.
A Transaction Reference can be created in a previous month so I am trying to exclude those transactions from the final count - the first thought was to use a "WHERE IN" type approach, but the outcome is always 0 which is definitely wrong as when I execute the queries in isolation, there are entries in the subquery which should be excluded.
I have read that "WHERE IN" type queries aren't reliable especially when there are large data sets returned in the subquery, but I don't know how to rework this one to achieve the goal in this case, and going forward if this way of doing it is flawed which it appears to be.
Current query is shown below - thanks for your help:
SELECT Count(DISTINCT TransactionRef)
FROM Payments
WHERE Month(PaymentDate) = 8
AND Year(PaymentDate) = 2011
AND TransactionRef NOT IN
(SELECT DISTINCT TransactionRef
FROM Payments WHERE PaymentDate < '20110801')
EDIT
OK further to answers, it seems a null value was doing me wrong... thanks - here is the edited code in case anyone stumbles here in future:
SELECT Count(DISTINCT TransactionRef)
FROM Payments
WHERE Month(PaymentDate) = 8
AND Year(PaymentDate) = 2011
AND TransactionRef NOT IN
(SELECT DISTINCT TransactionRef
FROM Payments WHERE TransactionRef IS NOT NULL AND PaymentDate < '20110801')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果 TransactionRef 列中有任何 null,则 not in 将返回 false 。
使用存在。
如果 NULL 不是您的问题,那么您必须向我们提供更多信息
if the column TransactionRef has any null in it the not in will return false.
use Exists.
if NULLs are not your problem then you'll have to give us mroe info
我是完全错误的还是您的查询与此查询完全相同:
编辑:再读一遍,您只想获取八月份记录的付款吗?然后你可以简单地在 where 中使用 BETWEEN 。
你真正的需要是什么?
Am I completely wrong or your query is exactly the same as this one:
Edit: reading it again, do you want to only get those paymeents recorded in August? Then you could simply use a BETWEEN in the where.
what is your real need?
使用不存在
use not exists