我有一个名为maximo_audit的表,我试图只计算最新的actiondate记录,其中包含N的批准状态。我写了这个查询,但它需要永远运行
SELECT COUNT (*)
FROM (SELECT MAX (actiondate)
FROM timedetail t JOIN maximo_audit m ON m.recordid = t.quantity
WHERE approvalstatus = 'N'
AND t.tsdate BETWEEN '8-dec-2013' AND '21-dec-2013'
AND task2 IS NOT NULL
--and recordid = '1781891'
GROUP BY m.recordid
HAVING MAX (actiondate) IN (SELECT MAX (actiondate)
FROM maximo_audit ma
WHERE ma.recordid = m.recordid))
答案 0 :(得分:0)
通常使用显式连接有助于优化器。您还可以使用更简单的count(distinct)
替换子查询。
SELECT COUNT(DISTINCT m.recordid)
FROM timedetail t JOIN
maximo_audit m
ON m.recordid = t.quantity JOIN
(select ma.recordid, max(actiondate) as actiondate
from maximo_audit ma
group by ma.recordid
) ma
on ma.recordid = m.recordid and ma.actiondate = m.actiondate
WHERE approvalstatus = 'N' AND
t.tsdate BETWEEN '8-dec-2013' AND '21-dec-2013' AND
task2 IS NOT NULL;
having
子句可以用连接替换,因为当操作日期的最大值等于某个值时,其中一个操作日期将匹配该值。