我有这个查询需要 2 分钟才能执行,即使时间段不是那么长:
SELECT MTI.DeptID,
ShortEmployees.EmpID,
ShortEmployees.EmpName1 AS EmpName,
Sum(CASE
WHEN (BSR.BSTID = 3
AND bli.state IN (12, 13, 14)) THEN -1 * ((BLD.Qty / dbo.Getunitval(BLD.UnitID, BLD.MTID)) * BLD.Price - ((BLD.Qty / dbo.Getunitval(BLD.UnitID, BLD.MTID)) * BLD.Price * BLD.discount * 0.01))
ELSE ((BLD.Qty / dbo.Getunitval(BLD.UnitID, BLD.MTID)) * BLD.Price - ((BLD.Qty / dbo.Getunitval(BLD.UnitID, BLD.MTID)) * BLD.Price * BLD.discount * 0.01))
END) AS Total
FROM BLD
INNER JOIN BLI
ON BLD.BLNo = BLI.BLNo
INNER JOIN BSR
ON BLI.BLID = BSR.BLID
INNER JOIN ShortEmployees
ON BLI.EmpID = ShortEmployees.EmpID
INNER JOIN MTI
ON BLD.MTID = MTI.MTID
WHERE (MTI.DeptID = 'B')
AND (BLI.BLDate > Cast('2013-01-01 00:00:00' AS DATETIME))
AND (BLI.BLDate < Cast('2013-01-14 23:59:59' AS DATETIME))
AND ((BSR.BSTID = 2
AND bli.state IN (2, 6, 8, 9,
10, 12, 18))
OR (BSR.BSTID = 3
AND bli.state IN (12, 13, 14)))
GROUP BY ShortEmployees.EmpName1,
ShortEmployees.EmpID,
MTI.DeptID
ORDER BY Total DESC
我该如何优化它?
MTI:项目信息表。
BLI:账单表。
BLD:账单明细表。
ShortEmployees:销售员表。