I have this query which takes 2 minutes to execute even the time period is not that long:
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
How I can optimize it?
MTI: Items information table.
BLI: Bills table.
BLD: Bill details table.
ShortEmployees: Salesmen table.
Finally, I ended up converting that query into whole stored procedure and the difference is huge! now it takes 2 seconds only :), thanks everybody specially the hater spanky 😉