SQL Server Group By Very Slow unless using temp tables I have a simple query:

INSERT INTO #Values
SELECT 2, MONTH(f.Datum), SUM(Quant * Price) FROM r_Fakt_Otpr_Data fd INNER JOIN r_Fakture f ON fd.FK_Faktura = f.ID_Faktura 
WHERE f.Type = 2 AND f.Stock = @stock AND f.Year = @year
GROUP BY MONTH(f.Datum)


It has about 10000 records to go through. It takes more than a minute.

If I omit GROUP BY and SUM it runs in less than a second.

Now, funny thing, if I split the query into SELECT and GROUP BY separately, using temp table, it runs in less than a second again:

CREATE TABLE #ValuesBuff
(
    Type int,
    Mnth int,
    Value float
)

INSERT INTO #ValuesBuff
SELECT 2, MONTH(f.Datum), (Quant * Price) FROM r_Fakt_Otpr_Data fd INNER JOIN r_Fakture f ON fd.FK_Faktura = f.ID_Faktura 
WHERE f.Type = 2 AND f.Stock = @stock AND f.Year = @year

INSERT INTO #Values
SELECT 2, Mnth, Sum(Vakue) FROM #ValuesBuff
GROUP BY Mnth


Why would this be the case?

What should I do to instruct SQL Server to perform better. Obviously it is GROUP BY that is the culprit, but it's fairly simple query, and i can't wrap my head around it.

Best Regards,
Sounds like a bad plan to me - and possibly around statistics.

When you insert the data into a temp table, you can get statistics auto created on it.

If your statistics think there aren't many records for that combination of stock and year, it could choose a really bad plan. Try updating your statistics and seeing how it goes. Or put a better indexing strategy together, to help the join as well as the filter and grouping.

You could also post the sqlplans...