I need to calculate the total number of columns before the specified date in a table that currently has over 400 thousand rows and is ready to grow further. I found that the aggregated function SUM()
too slow for my purpose, because I could not get it faster than about 1500 ms for an amount of more than 50 thousand lines.
Please note that the code below is the fastest implementation I've found so far. In particular, filtering data from CustRapport
and saving it in a temporary table led to a 3-fold increase in performance. I also experimented with indexes, but they usually did it slower.
I would like the feature to be at least an order of magnitude faster. Any idea on how to achieve this? I came across http://en.wikipedia.org/wiki/Fenwick_tree . However, I would prefer that storage and computation be handled in SQL Server.
CustRapport
and CustLeistung
are views with the following definition:
ALTER VIEW [dbo].[CustLeistung] AS SELECT TblLeistung.* FROM TblLeistung WHERE WebKundeID IN (SELECT WebID FROM XBauAdmin.dbo.CustKunde) ALTER VIEW [dbo].[CustRapport] AS SELECT MainRapport.* FROM MainRapport WHERE WebKundeID IN (SELECT WebID FROM XBauAdmin.dbo.CustKunde)
Thanks for any help or advice!
ALTER FUNCTION [dbo].[getBaustellenstunden] ( @baustelleID int, @datum date ) RETURNS @ret TABLE ( Summe float ) AS BEGIN declare @rapport table ( id int null ) INSERT INTO @rapport select WebSourceID from CustRapport WHERE RapportBaustelleID = @baustelleID AND RapportDatum <= @datum INSERT INTO @ret SELECT SUM(LeistungArbeit) FROM CustLeistung INNER JOIN @rapport as r ON LeistungRapportID = r.id WHERE LeistungArbeit is not null AND LeistungInventarID is null AND LeistungArbeit > 0 RETURN END
Execution plan:
http://s23.postimg.org/mxq9ktudn/execplan1.png
http://s23.postimg.org/doo3aplhn/execplan2.png
source share