I have the following query, and because of a lot of SUM
function calls, my query is running too slow. I have a lot of records in my database and I would like to get
Since you are always grouping values based on a whole number of months, I would first group by month in a subquery in the from clause. This is similar to using a temporary table. Not certain if this would actually speed up your query.
SELECT f.id, f.[Title], f.Class,
SUM(CASE WHEN f.MonthDiff = 1 THEN col1 ELSE 0 END) as [Current - Last 30 Days Col1],
-- etc
FROM (
SELECT
b.id,
d.[Title],
e.Class,
DateDiff(Month, a.DateCol, GETDATE()) as MonthDiff,
Sum(a.col1) as col1,
Sum(a.col2) as col2
FROM tb1 a
INNER JOIN tb2 b on a.id = b.fid and a.col3 = b.col4
INNER JOIN tb3 c on b.fid = c.col5
INNER JOIN tb4 d on c.id = d.col6
INNER JOIN tb5 e on c.col7 = e.id
WHERE a.DateCol between DATEADD(YEAR,-2,GETDATE() and GETDATE()
GROUP BY b.id, d.Title, e.Class, DateDiff(Month, a.DateCol, GETDATE())
) f
group by f.id, f.[Title], f.Class