我正在运行一个查询来计算一些数字,它似乎运行得非常慢。这是在MSSQL服务器上。运行查询大约需要22秒,只返回34条记录。问题是我同时运行多个SUM,执行时间加起来。我已经将sql语句简化为我需要的准系统。我如何更快地运行?
SELECT
SUM(case when (claims.dateon >= '20161110' AND claims.dateon < '20161117') AND entries.errorCode NOT IN('DP','RB','WP','PE','OV') then entries.refundDue else 0.0 end) as rate1
FROM auditors
INNER JOIN claims
ON claims.auditorID = auditors.auditorID
AND claims.status='closed'
--AND (claims.dateon >= '20161020' AND claims.dateon < '20161117')
INNER JOIN entries
ON claims.rID = entries.rid
WHERE claims.status = 'closed'
AND (claims.dateon >= '20161020' AND claims.dateon < '20161117')
GROUP BY auditors.auditorID
答案 0 :(得分:0)
我会更像这样写这个查询:
SELECT auditor_id,
sum(case when c.dateon >= '20161110' AND c.dateon < '20161117' AND
e.errorCode NOT IN ('DP', 'RB', 'WP', 'PE', 'OV')
then e.refundDue else 0.0
end) as rate1
FROM auditors a INNER JOIN
claims c
ON c.auditorID = a.auditorID AND c.status ='closed' INNER JOIN
entries e
ON c.rID = e.rid
WHERE c.status = 'closed' AND (c.dateon >= '20161020' AND c.dateon < '20161117')
GROUP BY a.auditorID;
然后我会注意到没有必要加入审计员:
SELECT auditor_id,
sum(case when c.dateon >= '20161110' AND c.dateon < '20161117' AND
e.errorCode NOT IN ('DP', 'RB', 'WP', 'PE', 'OV')
then e.refundDue else 0.0
end) as rate1
FROM claims c INNER JOIN
entries e
ON c.rID = e.rid
WHERE c.status = 'closed' AND
(c.dateon >= '20161020' AND c.dateon < '20161117')
GROUP BY c.auditorID;
然后我建议索引:claims(status, dateon, rId, auditorId)
和entries(rid, error_code, refunddue)
。